views:

174

answers:

2

I have the following code:

var tempIdx = document.getElementById('cityBuild').selectedIndex;
var tempBuilding = document.getElementById('cityBuild').options[tempIdx].value;

// Do stuff with tempBuilding

I spent some time trying to do it in jQuery under the assumption it'd be easier, it wasn't. I tried what was given at this site but is never returned any of the values. Am I doing something wrong or is this something that jQuery simply doesn't do?

The item is a select box (single selection only) and I want to get the value from it.

+7  A: 

jQuery knows how to work with select elements. You can get the value as any other input:

var value = $('#cityBuild').val();
Eran Galperin
That gets the selected text, not the value of the option.
Teifion
I thought you wanted the selected text... getting the value is even simpler. Check out my update
Eran Galperin
Accepted for being the "righter" way.
Teifion
+4  A: 

Little variation to Eran answer:

var value = $('#cityBuild option:selected').val();

EDIT: now Eran is in the right. :)

tanathos
No need to do option:selected if you need only the value..
Eran Galperin
It works! Thank you very much :)
Teifion
Eran's answer is the right(er) way of doing it.
Paolo Bergantino
It is now; it wasn't, originally.
Craig Stuntz
Thank you, Craig :) Yes, it was different, i'll update my answer
tanathos