views:

413

answers:

3

How do I get the actual value (or text) of the item selected in an HTML select box? Here are the main methods I've tried...


document.getElementById('PlaceNames').value

$("#PlaceNames option:selected").val()

$("#PlaceNames option:selected").text()

And I've tried various variations on these. All I ultimately want to do is get that data and send it to a web service via AJAX, I just need the string representation of what the user selected. This seems like it should be really easy and I've even found a question similar to this here, but I'm still having issues getting it worked out. Google doesn't seem to be helping either. I feel like it must be due to some fundamental misunderstanding of Javascript and jQuery.

EDIT: I should mention that I'm using IE7

A: 

var plid = $('#PlaceNames').val();

val placename = $('#PlaceNames option[value=\''+plid.toString()+'\']').html();

MonkeyBrother
+1  A: 

Non-jQuery variant:

var select = document.getElementById('PlaceNames');
var value = select.options[select.selectedIndex].value;

Older jQuery variant:

var select = $('#PlaceNames:first')[0];
var value = select.options[select.selectedIndex].value;

Current jQuery variant:

var value = $('#PlaceNames:first').val();

I'm probably just being overly safe using :first.

tvanfosson
+5  A: 

$('#placeNames').val() returns the value of the selected option in the latest version of jQuery.

Eran Galperin
Ok, I'm an idiot. I was doing it this way initially and was getting null returned. Turns out I was using the Id for an empty list box on the page just below the one I should have been using. It's been a long day.
Carter