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.
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.
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.
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.
Your best option is to use the placeholder support in Select2 and include a blank option tag as your default selection.
A more direct way ..
$('#select2-' + $id + '-container').find('.select2-selection__placeholder').text('Your Text');
where $id
is the id
of the select element
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
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