How to use placeholder as default value in select2 framework

To get the chosen value of a select2 I'm using:

var x = $("#select").select2('data');
var select_choice = x.text

The problem is this throws an error if not value has been selected and I was wondering if there was any way to make it return the placeholder if no option is selected


Solution 1:

You have to add an empty option (i.e. <option></option>) as a first element to see a placeholder.

From Select2 official documentation :

"Note that because browsers assume the first option element is selected in non-multi-value select boxes an empty first option element must be provided (<option></option>) for the placeholder to work."

Hope this helps.

Example:

<select id="countries">
    <option></option>
    <option value="1">Germany</option>
    <option value="2">France</option>
    <option value="3">Spain</option>
</select>

and the Javascript would be:

$('#countries').select2({
    placeholder: "Please select a country"
});

Solution 2:

Put this in your script file:

$('select').select2({
    minimumResultsForSearch: -1,
    placeholder: function(){
        $(this).data('placeholder');
    }
});

And then in HTML, add the following code:

<select data-placeholder="Your Placeholder" multiple>
    <option></option> <------ this is where your placeholder data will appear
    <option>Value 1</option>
    <option>Value 2</option>
    <option>Value 3</option>
    <option>Value 4</option>
    <option>Value 5</option>
</select>

Solution 3:

$('#ddlSelect').prepend('<option selected=""></option>').select2({placeholder: "Select Month"});

Solution 4:

$("#e2").select2({
   placeholder: "Select a State",
   allowClear: true
});
$("#e2_2").select2({
   placeholder: "Select a State"
});

The placeholder can be declared via a data-placeholder attribute attached to the select, or via the placeholder configuration element as seen in the example code.

When placeholder is used for a non-multi-value select box, it requires that you include an empty tag as your first option.

Optionally, a clear button (visible once a selection is made) is available to reset the select box back to the placeholder value.

https://select2.org/placeholders

Solution 5:

This worked for me:

$('#SelectListId').prepend('<option selected></option>').select2({
    placeholder: "Select Month",
    allowClear: true
});

Hope this help :)