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
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.
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.
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.
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.
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" });
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With