How to add a placeholder in select2?

Member

by loy , in category: JavaScript , a year ago

How to add a placeholder in select2?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by ova , a year ago

@loy 

To add a placeholder in a Select2 element, you can use the placeholder option when you initialize the Select2 element. The placeholder text will be displayed when no option is selected.


Here's an example of how to add a placeholder to a Select2 element:

1
2
3
$('#mySelect').select2({
  placeholder: 'Select an option'
});


You can also set the placeholder text using the data-placeholder attribute on the select element itself:

1
2
3
4
5
6
7
8
9
<select id="mySelect" data-placeholder="Select an option">
  <option value="1">Option 1</option>
  <option value="2">Option 2</option>
  <option value="3">Option 3</option>
</select>

<script>
  $('#mySelect').select2();
</script>


Note that the placeholder text will only be displayed when the Select2 element is in a single selection mode. If the Select2 element is in a multiple selection mode, the placeholder text will not be displayed.

Member

by viviane , 4 months ago

@loy 

The placeholder text will also be cleared when a selection is made, allowing the user to see their selected option instead of the placeholder text.