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.
The change event occurs when the value of an element has been changed (only works on <input>, <textarea> and <select> elements). The change() method triggers the change event, or attaches a function to run when a change event occurs. Note: For select menus, the change event occurs when an option is selected.
To get the value of a select or dropdown in HTML using pure JavaScript, first we get the select tag, in this case by id, and then we get the selected value through the selectedIndex property. The value "en" will be printed on the console (Ctrl + Shift + J to open the console).
Syntax of jQuery Select Option$(“selector option: selected”); The jQuery select option is used to display selected content in the option tag. text syntax is below: var variableValue = $(“selector option: selected”).
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With