.val () returning ATTRIBUTE value not content <option>

I am currently adding my own jquery code to a site created and hosted by a third party (so I cannot edit the HTML to remove attributes, etc.). I am trying to return the value of the selected item in a dropdown (for example this one goes from 100 to 500 in increments of 100), 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 happens when I select an option from the dropdown, the return value is 234 instead of 100, 235 instead of 200, etc.

I'm lost on how to return the content of the option element instead of the value of the value attribute?

+3


source to share


4 answers


Expected Behavior - .val()

Selection is the value of the selected item. You must use



var dropDowns = $( "#ctl00_cpMainBody_OptionCalc_Quantities option:selected" ).text();

      

+2


source


This is expected behavior. To get your inner text instead, you need to get the selected option and get its text like this:



function displayVals() {
  var dropDowns = $( "#ctl00_cpMainBody_OptionCalc_Quantities option:selected" ).text();
  $( "#displaying" ).html( "<strong>Value:</strong> " + dropDowns);
}

      

+1


source


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 will get a list of all parameters, something like

100
200
300
400
500

      

+1


source


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

      

-1


source







All Articles