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 sel
Arrow function has a different scope than function,
this.value
will give undefined for an arrow function.
To fix use
$('select').on('change',(event) => {
alert( event.target.value );
});
This is what worked for me. Tried everything else with no luck:
<html>
<head>
<title>Example: Change event on a select</title>
<script type="text/javascript">
function changeEventHandler(event) {
alert('You like ' + event.target.value + ' ice cream.');
}
</script>
</head>
<body>
<label>Choose an ice cream flavor: </label>
<select size="1" onchange="changeEventHandler(event);">
<option>chocolate</option>
<option>strawberry</option>
<option>vanilla</option>
</select>
</body>
</html>
Taken from Mozilla
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>
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();
});
For all selects, invoke this function.
$('select').on('change', function()
{
alert( this.value );
});
For only one select:
$('#select_id')
jQuery get value of select html elements using on Change event
For Demo & More Example
$(document).ready(function () {
$('body').on('change','#select_box', function() {
$('#show_only').val(this.value);
});
});
<!DOCTYPE html>
<html>
<title>jQuery Select OnChnage Method</title>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<select id="select_box">
<option value="">Select One</option>
<option value="One">One</option>
<option value="Two">Two</option>
<option value="Three">Three</option>
<option value="Four">Four</option>
<option value="Five">Five</option>
</select>
<br><br>
<input type="text" id="show_only" disabled="">
</body>
</html>