I want to change the placeholder on a select2 enhancing control upon an event.
So I've got this...
<select id="myFoo" placeholder="Fight some foo...">
...which is then enhanced:
init: function(){
$('#myFoo').select2();
},
...so now it has its correct placeholder.
But then I want it to react to an event and clear the placeholder...
someButtonPress: function(){
// $('#myFoo').placeholder("");
// $('#myFoo').attr('placeholder', "");
// $('#myFoo').select2('placeholder',"");
// $('#myFoo').select2({placeholder:""});
// none of these work
}
This seems so basic, yet I'm stumped.
I can't find anything in the docs. Am I looking in the wrong place?
Neither of those options worked for me in the latest version of Select2 (4.0.13) with a multiple select as the placeholder was indeed a search input. This finally worked:
$.fn.setSelect2Placeholder = function (placeholder) {
$(this).data('select2').selection.placeholder.text = placeholder;
$(this).trigger("change");
};
With that function I can update the placeholder of the select calling the function setSelect2Placeholder
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)placeholder
internal option or changing the related data attributesetPlaceholder
that sets the new placeholer.Hope that helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With