select2: programmatically controlling placeholder
Update
If you've set placeholder via HTML data-placeholder
attribute, you need to change it and not the internal option, so it will look as Fabian H. suggests:
$select.attr("data-placeholder", "New placeholder text");$select.data("select2").setPlaceholder();
Or if not, use an internal option select2.opts.placeholder
:
var select2 = $select.data("select2");select2.opts.placeholder = "New placeholder text";select2.setPlaceholder();
This is not perfect of course, but way better than hacking select2 generated HTML.
this.$select.data("select2")
gets you the internal select2 object, so you get access to its properties and methods (not only to those exported for use from outside)- Next I'm updating the
placeholder
internal option or changing the related data attribute - Finally I'm triggering internal method
setPlaceholder
that sets the new placeholer.
Hope that helps!
if you want to dynamically change the placeholder, don't set it on HTML
<select id="myFoo">
set it on jQuery
$('#myFoo').select2({ placeholder: "your placeholder"});
then update it like this
someButtonPress: function(){$('#myFoo').select2({ placeholder: "change your placeholder" });}
it works for me, hope it helps.
To update the placeholder of a Select2 with remote data (AJAX/JSONP) use this code:
$input = $("input#e7");$input.attr("data-placeholder", "New placeholder");var select2 = $input.data("select2");select2.setPlaceholder();
Credits to Brocks response.