Can anyone please tell me why doesn't this work on Google Chrome:
val = document.form.option[document.form.selectedIndex].value;
How should I get around this so that other browsers (like IE and FF) don't get screwed up.
Many thanks in advance.
Can anyone please tell me why doesn't this work on Google Chrome:
val = document.form.option[document.form.selectedIndex].value;
How should I get around this so that other browsers (like IE and FF) don't get screwed up.
Many thanks in advance.
Try this:
<select id="option">
....
</select>
then
val = $('#option').val();
It's because you're not actually selecting a form element. It should be something like this (I pretend that your select is named myselect
):
var formElement=document.getElementsByName("myselect")[0]; /* Select the form element */
var val=formElement.options[formElement.selectedIndex].value; /* Grab its value */
Here's an example in action.
$('select.foo').val(); // get the value from a dropdown select even easier
jQuery (1.4.2) code for function val
when element is a select
if ( jQuery.nodeName( elem, "select" ) ) {
var index = elem.selectedIndex,
values = [],
options = elem.options,
one = elem.type === "select-one";
// Nothing was selected
if ( index < 0 ) {
return null;
}
// Loop through all the selected options
for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) {
var option = options[ i ];
if ( option.selected ) {
// Get the specifc value for the option
value = jQuery(option).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
}