Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change placeholder in select2?

How do I change the data placeholder with select2?

So far I've tried this.

$("#city").select2({placeholder:"foo"});

And this...

$("#city").attr("data-placeholder","bar");

But neither works.

like image 718
Bill Avatar asked Sep 28 '13 03:09

Bill


People also ask

How to set select2 placeholder?

In order to use a placeholder with a single-value select box, you must include a blank <option></option> tag as the first option. As long as the select box has the multiple attribute set, Select2 will automatically pick this up.

How do I change the placeholder text?

The “placeholder” property is used to get or set the placeholder of an input text. This can be used to change the placeholder text to a new one. The element is first selected using a jQuery selector. The new placeholder text can then be assigned to the element's placeholder property.

How do you select placeholder style?

The ::placeholder selector selects form elements with placeholder text, and let you style the placeholder text. The placeholder text is set with the placeholder attribute, which specifies a hint that describes the expected value of an input field.

How do I stop select2 from auto selecting the first option?

Your best option is to use the placeholder support in Select2 and include a blank option tag as your default selection.


2 Answers

A more direct way ..

$('#select2-' + $id + '-container').find('.select2-selection__placeholder').text('Your Text');

where $id is the id of the select element

like image 158
Ken Kin Avatar answered Sep 21 '22 14:09

Ken Kin


You can also do it like this in the template (html) level. Just be sure to assign a blank (e.g. "") string on your first tag.

<select id="city" data-placeholder="Select Anything">
  <option value=""></option>
  <option value="option1">Option 1</option>
  <option value="option2">Option 2</option>
</select>

or we can simply add a data attribute for placeholder via javascript and it should happen before select2 gets initialized.

$('#city').data('placeholder','This is a placeholder');

DEMO

like image 30
wdonayredroid Avatar answered Sep 24 '22 14:09

wdonayredroid