How to Get Value of Select OnChange in jQuery
Today’s post will teach about getting the changed values of the select
in jQuery.
OnChange
in jQuery
jQuery provides a change
method that either binds an event handler to the JavaScript change event or fires that event on an element.
Syntax:
.change(handler)
A handler
is a function that needs to be executed when the change
event fires. The change
event is sent to an element as soon as an element’s value changes.
This event is limited to input elements, text box fields, and select elements.
For checkboxes, and radio buttons, the event fires immediately when the user makes a mouse selection, but for other element types, the event is delayed until the element loses focus. You can find more information about the onchange
in this documentation.
Let’s understand it with the following example.
<select>
<option value="mumbai">Mumbai</option>
<option value="goa">Goa</option>
</select>
$('select').on('change', function() {
console.log(this.value);
});
In the above example, we have defined the 2 select
options. The event handler can be bound to the select
box.
When the user selects an option, jQuery will detect that change and the change
function is fired.
After an event is fired, it will return the selected value. Try to run the above code snippet in any browser that supports jQuery, and it will show the below result.
Output:
"goa"
"mumbai"
Shraddha is a JavaScript nerd that utilises it for everything from experimenting to assisting individuals and businesses with day-to-day operations and business growth. She is a writer, chef, and computer programmer. As a senior MEAN/MERN stack developer and project manager with more than 4 years of experience in this sector, she now handles multiple projects. She has been producing technical writing for at least a year and a half. She enjoys coming up with fresh, innovative ideas.
LinkedIn