How To On Change In Jquery

In web development, jQuery is a popular and powerful JavaScript library that simplifies various tasks such as HTML document traversal, manipulation, event handling, and animation. One common task is detecting when a user interacts with an HTML form element, such as a dropdown menu or text input field. This can be accomplished using the on change event handler in jQuery.

In this blog post, we will explore how to use the on change event handler in jQuery to perform actions when a user interacts with form elements. Let’s get started!

Step 1: Include jQuery Library

To use jQuery, you must first include the library in your HTML file. You can download the library from the official jQuery website or include it using a Content Delivery Network (CDN) like Google or Microsoft. Here’s an example of how to include jQuery using Google’s CDN:




    <meta charset="UTF-8">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>


    <h2>Step 2: Create an HTML Form Element</h2>
<p>
    Next, create an HTML form element that the user will interact with. For this example, we will use a simple dropdown menu:
</p>

[sourcecode language="html"]
<select id="my-dropdown">
    <option value="option1">Option 1</option>
    <option value="option2">Option 2</option>
    <option value="option3">Option 3</option>
</select>

Step 3: Attach the ‘on change’ Event Handler

Now that we have our form element, we can attach the on change event handler using jQuery. The syntax for this is:

$('selector').on('change', function() {
    // Your code here
});

Replace selector with the appropriate selector for your form element. In our example, we will use the #my-dropdown ID selector:

$('#my-dropdown').on('change', function() {
    // Your code here
});

Step 4: Add Your Custom Code

Inside the on change event handler, you can write your custom code that will execute when the form element is interacted with. In our example, let’s display an alert box with the selected option’s value:

$('#my-dropdown').on('change', function() {
    var selectedOptionValue = $(this).val();
    alert('You selected: ' + selectedOptionValue);
});

Putting It All Together

Here’s the complete code for our example:




    <meta charset="UTF-8">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>


    <select id="my-dropdown">
        <option value="option1">Option 1</option>
        <option value="option2">Option 2</option>
        <option value="option3">Option 3</option>
    </select>

    <script>
        $('#my-dropdown').on('change', function() {
            var selectedOptionValue = $(this).val();
            alert('You selected: ' + selectedOptionValue);
        });
    </script>


And that’s it! You now know how to use the on change event handler in jQuery to perform actions when a user interacts with a form element. Happy coding!