jQuery get value of select onChange
jQuery get value of select onChange
Question
I was under the impression that I could get the value of a select input by doing this $(this).val();
and applying the onchange
parameter to the select field.
It would appear it only works if I reference the ID.
How do I do it using this.
Accepted Answer
Try this-
$('select').on('change', function() {
alert( this.value );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value="1">One</option>
<option value="2">Two</option>
</select>
You can also reference with onchange event-
function getval(sel)
{
alert(sel.value);
}
<select onchange="getval(this);">
<option value="1">One</option>
<option value="2">Two</option>
</select>
Read more… Read less…
I was under the impression that I could get the value of a select input by doing this $(this).val();
This works if you subscribe unobtrusively (which is the recommended approach):
$('#id_of_field').change(function() {
// $(this).val() will work here
});
if you use onselect
and mix markup with script you need to pass a reference to the current element:
onselect="foo(this);"
and then:
function foo(element) {
// $(element).val() will give you what you are looking for
}
This is helped for me.
For select:
$('select_tags').on('change', function() {
alert( $(this).find(":selected").val() );
});
For radio/checkbox:
$('radio_tags').on('change', function() {
alert( $(this).find(":checked").val() );
});
Try the event delegation method, this works in almost all cases.
$(document.body).on('change',"#selectID",function (e) {
//doStuff
var optVal= $("#selectID option:selected").val();
});
You can try this (using jQuery)-
$('select').on('change', function()
{
alert( this.value );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
</select>
Or you can use simple Javascript like this-
function getNewVal(item)
{
alert(item.value);
}
<select onchange="getNewVal(this);">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
</select>
$('#select_id').on('change', function()
{
alert(this.value); //or alert($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="select_id">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
</select>