Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
24
rated 0 times [  29] [ 5]  / answers: 1 / hits: 25311  / 10 Years ago, tue, september 9, 2014, 12:00:00

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.


More From » jquery

 Answers
18

DEMO



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

[#69524] Saturday, September 6, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
valentinam

Total Points: 166
Total Questions: 117
Total Answers: 81

Location: Puerto Rico
Member since Sun, Jun 27, 2021
3 Years ago
;