Anuj TBE Anuj TBE - 2 months ago 11
Javascript Question

Get the value of selected option using jQuery

I have an array of select field and want to get the value of selected option using jQuery.

Select field is like

<select name="a[]" onchange="getValue(this)">
<option value="11">11</option>
<option value="12">12</option>
</select>
<select name="a[]" onchange="getValue(this)">
<option value="21">21</option>
<option value="22">22</option>
</select>


and my javascript code is

function getValue(ele) {
alert(ele.val());
}


But it is not working.

Answer

The val() is a jQuery method which can't use with DOM object. To get value use value property of the element instead.

function getValue(ele) {
  alert(ele.value);
  // with jQuery it should be
  // alert($(ele).val());
}

function getValue(ele) {
  alert(ele.value);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="a[]" onchange="getValue(this)">
  <option value="11">11</option>
  <option value="12">12</option>
</select>
<select name="a[]" onchange="getValue(this)">
  <option value="21">21</option>
  <option value="22">22</option>
</select>


Since you are tagged jQuery in your question use change() event handler, Inside the change event callback this refers to the corresponding dom object.

// select element with the name  attribute equals 
// selector can be used and then bind event handler
$('[name="a[]"]').change(function() {
  // get the value
  alert(this.value)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="a[]">
  <option value="11">11</option>
  <option value="12">12</option>
</select>
<select name="a[]">
  <option value="21">21</option>
  <option value="22">22</option>
</select>

Comments