vendredi 19 février 2016

Getting Multiple Select Box Options to Stay Selected Using Chosen Select

I'm trying to get the selected options to stay selected in the following select box. (The select box resides in the Menus page in WordPress admin). I've verified the data is being saved to the database, but I'm having difficulty figuring out to get the data back from the database to mark the options selected for a given select box. There are multiple select boxes on the page.

The select box makes use of the Chosen Select jQuery plugin. Here's a question and answer providing some guidance on marking the options selected with JS: Chosen select an option by default with jQuery. I couldn't get it to work having multiple select boxes on the page.

<script type="text/javascript">
    jQuery(document).ready(function($){ 
        $(".chzn-select").chosen();
    });
</script>

<select name="locations[<?php echo $item_id; ?>]" id="edit-menu-item-visibility-<?php echo $item_id; ?>" class="chzn-select" multiple="true">
    <option value="DZ">Algeria</option>
    <option value="AS">American Samoa</option>
    <option value="AD">Andorra</option>
    ...

This is how the data gets to the database:

function update_option_text( $menu_id, $menu_item_db_id, $args ) {
    $meta_value = get_post_meta( $menu_item_db_id, 'locations', true );
    $new_meta_value = stripcslashes( $_POST['locations'][$menu_item_db_id] );
    if( '' == $new_meta_value ) {
        delete_post_meta( $menu_item_db_id, 'locations', $meta_value );
    }
    elseif( $meta_value !== $new_meta_value ) {
        update_post_meta( $menu_item_db_id, 'locations', $new_meta_value );
    }
}

Below is my non-working attempt. If I understand correctly, the values can be set to selected with JS. But I couldn't get that to work either. Any assistance is greatly appreciated.

<option value="AF" <?php $val = implode(",",get_post_meta( $menu_item_db_id, 'locations', true )); if(in_array("AF", $val)){echo "selected='selected'";}else{echo "";} ?> >Afghanistan</option>

Here is how the original text input worked:

<input
    type="text" 
    class="widefat code" 
    id="edit-menu-item-visibility-<?php echo $item_id; ?>" 
    name="locations[<?php echo $item_id; ?>]" 
    value="<?php echo esc_html( get_post_meta( $item_id, 'locations', true ) ); ?>" />
    <?php echo 'Enter 2-digit country codes separated by commas, e.g. US,CA,SG' ?></br>

The entire file can be found here.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire