How to change placeholder in select2?

How to change data placeholder using select2?

So far I have tried this.

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

And this...

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

But does not work.

+6
source share
5 answers

I found that if I just installed attr, for example. $("#city").attr('data-placeholder', 'bar') , no effect. However, if I set attr and then call $("#city").select2() with no arguments, then the placeholder is updated.

eg.

 $("#city").attr("data-placeholder","bar"); $("#city").select2(); 
+7
source

For other people looking for an attribute solution to avoid changing the JS code. I just needed to consider this for a project, and it seems like select2 just needs the data-placeholder = "" attribute.

 <select id="city" data-placeholder="my placeholder"></select> 

See more here: selection link2 for selection

+3
source

Put it in the html that your locator uses as follows:

 <select id="city" placeholder="my placeholder"></select> 
+1
source

You can also do this at the template level (html). Just remember to assign an empty string (like "") in your first tag.

 <select class="test-select2" data-placeholder="Select Anything"> <option value=""></option> <option value="option1">Option 1</option> <option value="option2">Option 2</option> </select> 

Demo

+1
source

For select2 version 4, I specified the placeholder text in js init code, and then updated it with $select.select2{placeholder:"updated text..."}

0
source

Source: https://habr.com/ru/post/954826/


All Articles