April 24, 2012

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
multiple="multiple">
elements, the .val() method returns an array
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
multiple="multiple">
elements, the .val() method returns an array
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();
});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!