简体   繁体   中英

jQuery Select2 placeholder doesn't work when defined inline?

I have the following multiple drop-down lists defined using select2 but the placeholders don't work?

<select class="js-select2" multiple="multiple" placeholder="Select State">
     <option value="AK">Alaska</option>
     <option value="HI">Hawaii</option>
</select>

<select class="js-select2" multiple="multiple" placeholder="Select Fruits">
     <option value="Apples">Apples</option>
     <option value="Oranges">Oranges</option>
</select>

<script>
    $(".js-select2").select2({
      // placeholder: 'Select an option...'
   });

</script>

It only works if I define the placeholder inside the select2 option list (commented out above) but I want to use a single class to initialize all select2 multiselects drop-downs and display different placeholders.

Is it possible to achieve this?

For a quick workaround, you can pass the value of the attribute to the placeholder option:

 $(".js-select2").each(function() {
    $(this).select2({
       placeholder: $(this).attr('placeholder')
   });
 });

This does not work when using $(".js-select2").select2() directly, I assume in that context this doesn't point to the right object (or something like that). But if you use an each loop to initialize it on each element separately, it works.

https://jsfiddle.net/84whaced/


Alternatively, it should work if you use data-placeholder in the HTML (amazing what we can find out once we check the documentation, right?), see https://select2.github.io/options.html#data-attributes - https://jsfiddle.net/84whaced/1/

This would be the preferred option, I think.

You can use the data-placeholder for different placeholder for every select

$('select').select2({
    placeholder: function(){
        $(this).data('placeholder');
    }
});

<select class="js-select2" multiple="multiple"  data-placeholder="Select State">
     <option value="AK">Alaska</option>
     <option value="HI">Hawaii</option>
</select>

<select class="js-select2" multiple="multiple"  data-placeholder="Select Fruits">
     <option value="Apples">Apples</option>
     <option value="Oranges">Oranges</option>
</select>

You can check the Demo as well.

It will work as:

If we just set the attr eg $("#state").attr('data-placeholder', 'Select State') , there will no effect.

However, if we set the attr and then call $("#state").select2() with no arguments, then the placeholder updates.

$("#state").attr("data-placeholder","Select State");
$("#state").select2();

Maybe you have similar ids on your page. JS'll select latest id by default. Try to change them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM