val() on <option> returns text instead of value in ie7
Question by Johan
$(this).find('select option:selected').each(function (i, val) {
var selectedValue = $(val).val(); //this returns the text from the option instead of the value
});
Is this a known issue in ie7? I didnt find any info about it? Possible workarounds? Thanks
Answer by SiGanteng
According to the docs at http://api.jquery.com/val/
.val()
is only applicable to
The .val() method is primarily used to get the values of form elements
such as input, select and textarea. In the case of<select
elements, the .val() method returns an array
multiple="multiple">
containing each selected option; if no option is selected, it returns
null.
To achieve what you want, you could just iterate over the select
and call .val()
on it, your original code effectively is calling val()
on option
, not the actual select
element, which is why it doesn’t really work.
$(this).find('select').each(function (i, val) {
var selectedValue = $(this).val();
});
val()
has an added bonus of having the capability to return an array of values in case of multiple
select: (emphasize mine)
The .val() method is primarily used to get the values of form elements
such as input, select and textarea. In the case of<select
elements, the .val() method returns an array
multiple="multiple">
containing each selected option; if no option is selected, it returns
null.
Answer by Starx
It is an expected behavior, since you asking for the value of the option and not the element itself.
Do not overcomplicate things.
$(this).find('select').each(function() {
var val = $(this).val();
});