Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select2: programmatically controlling placeholder

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?

like image 289
DaveC426913 Avatar asked Jun 03 '13 17:06

DaveC426913


2 Answers

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

like image 89
lechonex Avatar answered Oct 11 '22 06:10

lechonex


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.

  1. 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)
  2. Next I'm updating the placeholder internal option or changing the related data attribute
  3. Finally I'm triggering internal method setPlaceholder that sets the new placeholer.

Hope that helps!

like image 24
Brock Avatar answered Oct 11 '22 06:10

Brock