MOTOSHARE 🚗🏍️

Rent Bikes & Cars Directly from Owners

Motoshare connects vehicle owners with people who need bikes and cars on rent. Owners earn from idle vehicles, and renters get flexible ride options.

Visit Motoshare

How to add placeholder to select2.js

JavaScript

Single select placeholders

<select class="js-example-placeholder-single js-states form-control">
  <option></option>
</select>

$(".js-example-placeholder-single").select2({
    placeholder: "Select a state",
    allowClear: true
});

Multi-select placeholders

<select class="js-example-placeholder-multiple js-states form-control" multiple="multiple"></select>
$(".js-example-placeholder-multiple").select2({
    placeholder: "Select a state"
});

Using placeholders with AJAX

Select2 supports placeholders for all configurations, including AJAX. You will still need to add in the empty <option> if you are using a single select.

When using Select2 in single-selection mode, the placeholder option will be passed through the templateSelection callback if specified. You can use some additional logic in this callback to check the id property and apply an alternative transformation to your placeholder option:

$('select').select2({
  templateSelection: function (data) {
    if (data.id === '') { // adjust for custom placeholder values
      return 'Custom styled placeholder text';
    }

    return data.text;
  }
});
Amardeep Dubey
Latest posts by Amardeep Dubey (see all)
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
0
Would love your thoughts, please comment.x
()
x