select2: programmatically controlling placeholder

DaveC426913 picture DaveC426913 · Jun 3, 2013 · Viewed 25.1k times · Source

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?

Answer

Brock picture Brock · May 7, 2014

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!