I have a multiple select on my page, and I have an option disabled so that the user can't unselect them, but I can't work out how to get the value of the disabled option.
My code so far
// Get selected positions
var $selPositions = $('select#empPositions').val();
HTML
<select name="empPositions[]" id="empPositions" style="width: 370px;" multiple="" data-placeholder="Choose a Position" required="">
<option></option>
<optgroup label="Admin">
<option disabled="">There are no positions assigned to Admin</option>
</optgroup>
<optgroup label="Information Technology">
<option value="1" selected="" disabled="">IT Developer</option>
<option value="2">IT Geeks</option>
</optgroup>
Note the disabled option changes based on other variables, but it only gives me selected non-disabled values. Can anyone let me know if this can be done and how?
I'm using Chosen, hence why the disabled
option
Fiddle: http://jsfiddle.net/c5kn5w75/
I did find this article on the JQuery Bug Site which said
The long-standing logic in .val() ensures that we don't return disabled options in a select-multiple. The change just applies the same behavior for select-one now for consistency. You can get to the disabled option value through $("select").prop("selectedIndex") if you need it.
But that didn't work for me.
var opt = $('#empPositions option:selected').map(function(i,v) {
return this.value;
}).get(); // result is array
alert( opt );
Please bear in mind that when you submit the form disabled options wont be submitted even if they are selected. If you're submitting via AJAX, then you can grab the values as shown above.
Also bear in mind that $('option[disabled]').val()
will return the value of the first disabled option
element and $('option[disabled]:selected').val()
the value of the first selected disabled option.
If there's always just one selected disabled
option element you can target it using:
var opt = $('#empPositions option[disabled]:selected').val(); // result is string