Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 417
Gottfried Avatar asked Jan 28 '14 18:01

Gottfried


People also ask

How do you add a placeholder in Select 2?

Default selection placeholders$('select'). select2({ placeholder: { id: '-1', // the value of the option text: 'Select an option' } }); This is useful, for example, when you are using a framework that creates its own placeholder option.

How do I assign a value to Select2?

To dynamically set the "selected" value of a Select2 component: $('#inputID'). select2('data', {id: 100, a_key: 'Lorem Ipsum'}); Where the second parameter is an object with expected values.

How do I stop Select2 from auto selecting the first option?

This behaviour exists not because Select2 is forcing it, but because the browser is auto-selecting the first option for you. We can't control that, we can only work around it. Your best option is to use the placeholder support in Select2 and include a blank option tag as your default selection.

How do I add a placeholder to a select tag?

To add a placeholder to a select tag, we can use the <option> element followed by the disabled , selected , and hidden attribute. The disabled attribute makes the option unable to select. The selected attribute shows the text inside <option> element opening and closing tags.


2 Answers

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" }); 
like image 102
meherzi.sahbi Avatar answered Sep 24 '22 06:09

meherzi.sahbi


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> 
like image 31
Oleg Sevruk Avatar answered Sep 22 '22 06:09

Oleg Sevruk