How to use placeholder as default value in select2 framework
Asked Answered
C

16

69

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

Cleocleobulus answered 28/1, 2014 at 18:0 Comment(1)
= f.input :field, collection: Field.all, as: :select, input_html: { data: { placeholder: 'Choose your country' } }, label_method: :name, value_method: :alpha2, required: trueWoad
T
143

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."

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"
});
Thiol answered 20/8, 2014 at 16:41 Comment(2)
i dont understand. can you make me an example?Coquetry
How if i populate data from ajax?Cashier
F
58

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>
Finality answered 9/6, 2015 at 16:57 Comment(3)
IMO this is the best approach for both multiple and single selectsEnsoll
this works, but you need to add an empty option as first element in the select. Plus you don't need "minimumResultsForSearch: -1 " . i.e. in case you have only 1 result , you won't be able to select anything.Remanence
Per the docs, "placeholder" does not accept a function as a value. This only works because select2 uses data-* attributes to populate placeholderGemini
F
29
$('#ddlSelect').prepend('<option selected=""></option>').select2({placeholder: "Select Month"});
Fielder answered 1/11, 2016 at 17:11 Comment(4)
+1 In the current version the empty option has to be seleted though: $('#ddlSelect').prepend('<option selected=""></option>').select2({placeholder: "Select Month"});Dumpcart
This answer is incorrect. as prepend will be called after efter every allotment of the value. So if you have 1000 values, then you will get 1000 prepend.Cohl
@AnkurSoni what are you trying to say? This solution is working for me fineSmutch
This is cool solution, thx alot, i was struggling with "FORM SUBMITTING VIA AJAX WITH SELECT2 DROPDOWN"Arcade
S
15
$("#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

Suzannasuzanne answered 28/1, 2014 at 18:41 Comment(2)
Please note that the option list of the select field has to contain an empty option <option></option> that placeholders work for single select fields. For me kind of a bug.Henricks
This is a working example <select id="Select" style="width:100%"> <option></option> <option value="AK">AK</option> <option value="TN">TN</option> </select>Avarice
H
9

This worked for me:

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

Hope this help :)

Handlebar answered 31/1, 2018 at 21:0 Comment(1)
Esto funciono para miChappie
W
4

In the current version of select2 you just need to add the attribute data-placeholder="A NICE PLACEHOLDER". select2 will automatically assign the placeholder. Please note: adding an empty <option></option> inside the select is still mandatory.

<select id="countries" data-placeholder="***A NICE PLACEHOLDER***">
  <option></option>
  <option value="1">Germany</option>
  <option value="2">France</option>
  <option value="3">Spain</option>
</select>
Walkling answered 15/12, 2020 at 15:11 Comment(0)
P
3

Use a empty placeholder on your html like:

<select class="select2" placeholder = "">
    <option value="1">red</option>
    <option value="2">blue</option>
</select>

and in your script use:

$(".select2").select2({
        placeholder: "Select a color",
        allowClear: true
    });
Pseudo answered 12/5, 2017 at 14:42 Comment(0)
S
2

you can init placeholder in you select html code in two level such as:

<select class="form-control select2" style="width: 100%;" data-placeholder="Select a State">
   <option></option>
   <option>تهران</option>
   <option>مشهد</option>
   <option>اصفهان</option>
   <option>شیراز</option>
   <option>اهواز</option>
   <option>تبریز</option>
   <option>کرج</option>   
</select>

1.set data-placeholder attribute in your select tag 2.set empty tag in first of your select tag

Steverson answered 13/12, 2018 at 7:30 Comment(0)
W
1

I did the following:

var defaultOption = new Option();
defaultOption.selected = true;    
$(".js-select2").append(defaultOption);

For other options I use then:

var realOption = new Option("Option Value", "id");
realOption.selected = false;    
$(".js-select2").append(realOption);
Wellbeloved answered 24/2, 2017 at 12:33 Comment(0)
P
0

Try this.In html you write the following code.

<select class="select2" multiple="multiple" placeholder="Select State">
    <option value="AK">Alaska</option>
    <option value="HI">Hawaii</option>
</select>

And in your script write the below code.Keep in mind that have the link of select2js.

<script>
         $( ".select2" ).select2( { } );
 </script>
Percussion answered 8/4, 2016 at 9:21 Comment(0)
S
0

The simplest way to add empty "option" before all.

<option></option>

Example:

<select class="select2" lang="ru" tabindex="-1">
    <option></option>
    <option value="AK">Alaska</option>
    <option value="HI">Hawaii</option>
</select>

Also js code, if you need:

$(document).ready(function() {
    $(".select2").select2({
            placeholder: "Select a state",
            allowClear: true
        });
    });
}
Sachs answered 5/11, 2016 at 19:58 Comment(0)
B
0

I tried all this and in the end, simply using a title="text here" worked for my system. Note there is no blank option

<select name="Restrictions" class="selectpicker show-tick form-control" 
        data-live-search="true" multiple="multiple" title="Choose Multiple">
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
</select>
Bathypelagic answered 4/2, 2021 at 16:42 Comment(0)
H
0

All answers that include an empty option at first position of select element is correct, but only work when there's no option selected.

I used @Colin's solution - $('.wcl-select').prepend('<option selected=""></option>').select2({placeholder: "Select Month"}) - however when we've one option selected, we will have two options marked with selected, not correctly displaying the selected item:

Bug

I will check, before applying Select2, if there's any option selected, then create empty option in the first position:

$(".wcl-select").each(function(_, element) {
    if (!$(element).find('option[selected]').length) {
        $(element).prepend("<option value='' selected='selected'></option>");
    }
});

$(".wcl-select").select2({
    theme: "bootstrap-5",
    width: $(this).data('width') ? $(this).data('width') : $(this).hasClass('w-100') ? '100%' : 'style',
    placeholder: $(this).data('placeholder'),
    allowClear: false,
    closeOnSelect: true,
    multiple: false,
});
Hooknosed answered 24/1, 2024 at 2:32 Comment(0)
A
0

You can use the following code for placeholder as the default value.

JavaScript on page load:

$("#selectCountry").select2({
    multiple:true,
    maximumSelectionLength:1,
    placeholder:'YOUR PLACEHOLDER TEXT'
});
$("#selectCountry option:selected").remove();

HTML:

<select id="selectCountry">
  <option></option> <!-- this must be null -->
  <option>OPTION1</option>
  <option>OPTION2</option>
</select>
Acrolith answered 24/1, 2024 at 9:5 Comment(0)
H
-1

Just add this class in your .css file.

.select2-search__field{width:100% !important;}
Harrovian answered 8/7, 2020 at 16:0 Comment(0)
D
-2
$selectElement.select2({
    minimumResultsForSearch: -1,
    placeholder: 'SelectRelatives'}).on('select2-opening', function() {                                                                       $(this).closest('li').find('input').attr('placeholder','Select Relative');                            
});
Dak answered 23/2, 2016 at 14:32 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.