James Glass
James Glass

Reputation: 4300

Geting a value from select box using jQuery

I've got a simple select input and I'm using jQuery's .val() to get the selection from it.

For some reason, it is throwing a "Object doesn't support this property or method" error in Internet Explorer 8, the first error I've ever seen jQuery actaully throw.

I've replicated this error at http://jsfiddle.net/gWvwS

What am I doing wrong? Seems pretty straight forward to me...

Upvotes: 1

Views: 387

Answers (6)

Rob W
Rob W

Reputation: 348992

Your document contains an element with name display_entry_form. In IE, named elements are globally accessible through their name. So, you have to either use var (to declare a new, local variable[Need verification]), or choose another name.

var other_name = $('#display_entry_form').val();
alert(other_name);

Fiddle http://jsfiddle.net/gWvwS/5/

Upvotes: 1

Microfed
Microfed

Reputation: 2890

Javascript variables with the same name as DOM elements are not supported by IE. It appears that IE uses a common mechanism for addressing DOM elements by id and addressing javascript variables. Which means that whichever object (DOM element or javascript var) is declared later in the source is the one that gets used. This will likely cause an "object does not support this property or method" error when you try to access your javascript variable. (source)

This should work:

display_entry_form_value = $('#display_entry_form > option:selected').val();
alert(display_entry_form_value);

Upvotes: 2

Jonathan M
Jonathan M

Reputation: 17451

The <select> tag doesn't have a value attribute, but rather a selectedIndex attribute.

Upvotes: 0

Joe
Joe

Reputation: 82594

Try:

var isplay_entry_form = $('#display_entry_form').val();
alert(isplay_entry_form);

display_entry_form on the global window is actually the element. It's much less known, because it's really bad and shouldn't be used. So you are overwriting it in IE.

Fixed Example for IE8: http://jsfiddle.net/gWvwS/7/

Upvotes: 3

MOleYArd
MOleYArd

Reputation: 1268

I suppose it has to do with, that value belongs to option, not to select.

Try

$('select#display_entry_form option:selected').val();

Upvotes: 1

Teddy
Teddy

Reputation: 18572

I updated jsfiddle to correct code:

http://jsfiddle.net/gWvwS/6/

Upvotes: 0

Related Questions