Question

I'm having trouble getting my jQuery snippet to work properly due to a 'conflict' with the jQuery plugin 'chosen'. I'm using Wordpress in case that matters.

I want to set the selected attribute in several <option> tags, using

jQuery( document ).ready(function() {
var arr = ["1", "2"];
jQuery("#location option").each(function () {
    if (jQuery.inArray(jQuery(this).val(), arr) != -1) {
        jQuery(this).prop('selected', true);
    };
});
});

html output

 <select name="location[]" multiple="multiple" id="location" class="postform" style="display: none;">
        <option value="-1">Select a location</option>
        <option class="level-0" value="1">Location A</option>
        <option class="level-0" value="2">Location B</option>
        <option class="level-0" value="3">Location C</option>
    </select>

I feel like I'm providing to little details here to solve the issue, but I'm unsure what additional code to post here.

When disabling (not enqueueing) the chosen plugin (chosen.jquery.min.js), everything works fine. Still, I would like the chosen plugin to work.

Was it helpful?

Solution

Your code does work, although it's the order in which you call it in - is what may be stumbling over a little. As demostrated in this Fiddle.

functions.php

<?php 
    /**
     *  Load:
     *    css; chosen; jquery.
    **/
    function wordpress_scripts() {

        wp_enqueue_style( 
                   'chosen.css', 
                   get_stylesheet_uri() 
                 );

        wp_enqueue_script( 
                   'chosen.js', 
                   get_template_directory_uri() . '/js/chosen.js', 
                   array('jquery')
                 );

        wp_enqueue_script( 
                   'myscript.js', 
                   get_template_directory_uri() . '/js/myscript.js', 
                   array('jquery')
                 );
    }

    add_action( 'wp_enqueue_scripts', 'wordpress_scripts' );
?>

myscript.js

<script>
    jQuery(document).ready(function(){
         var arr = ["1", "2"];
         jQuery("#location option").each(function () {
             if (jQuery.inArray(jQuery(this).val(), arr) != -1) {
                 jQuery(this).prop('selected', true);
             };
         });

         if ( typeof jQuery.fn.chosen !== 'undefined' )
             jQuery("#location").chosen();
    });
</script>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top