Reputation: 73
I'm currently adding my own jquery code to a site built and hosted by a third party (so I can't edit the HTML to remove attributes, etc). I'm trying to return the value of the currently selected item of a drop down box (for example this one goes from 100 to 500 in steps of 100), the HTML:
<select name="ctl00$cpMainBody$OptionCalc$Quantities" onchange="javascript:setTimeout('__doPostBack(\'ctl00$cpMainBody$OptionCalc$Quantities\',\'\')', 0)" id="ctl00_cpMainBody_OptionCalc_Quantities" class="form-control">
<option selected="selected" value="234">100</option>
<option value="235">200</option>
<option value="236">300</option>
<option value="237">400</option>
<option value="238">500</option>
</select>
and this is my jquery:
function displayVals() {
var dropDowns = $( "#ctl00_cpMainBody_OptionCalc_Quantities" ).val();
$( "#displaying" ).html( "<strong>Value:</strong> " + dropDowns);
}
$(document).on("change", "select", displayVals);
displayVals();
What's happening is whenever I select an option from the drop down, the returned value is 234 instead of 100, 235 instead of 200, etc.
I'm lost on how to have it return the content of the option element instead of the value of the value attribute?
Upvotes: 3
Views: 428
Reputation: 716
$( "#ctl00_cpMainBody_OptionCalc_Quantities option:selected" ).text()
Upvotes: -1
Reputation: 360
This is expected behavior -- the .val()
of a select is the value of the selected item. You should use
var dropDowns = $( "#ctl00_cpMainBody_OptionCalc_Quantities option:selected" ).text();
Upvotes: 2
Reputation: 19573
if you want to get the text value, you can do this
$("#ctl00_cpMainBody_OptionCalc_Quantities option:selected").text();
if you do $("#ctl00_cpMainBody_OptionCalc_Quantities").text();
without :selected
, you'll get a listing of every option, something like
100
200
300
400
500
Upvotes: 1
Reputation: 5948
That's the expected behaviour. To retrieve their inner text instead, you need to get the selected option and get its text, as follows:
function displayVals() {
var dropDowns = $( "#ctl00_cpMainBody_OptionCalc_Quantities option:selected" ).text();
$( "#displaying" ).html( "<strong>Value:</strong> " + dropDowns);
}
Upvotes: 1