jquery
  1. jquery-change

JQuery change()

JQuery change() is a method that binds an event handler to the "change" JavaScript event. This event is triggered when the value of an element is changed by a user or by JavaScript.

Syntax

$(selector).change(function)

The change() method takes a function as a parameter. This function is called whenever the change event is triggered for the selected element.

Use

JQuery change() is most commonly used with input elements, such as text fields, radio buttons, and checkboxes. It allows you to register a function that will be executed whenever the value of the selected element is changed, providing a powerful tool for creating interactive and dynamic user interfaces.

Example

Here is an example of using JQuery change() to update the text of a message box whenever a user selects a new option from a drop-down menu:

<!DOCTYPE html>
<html>
<head>
    <title>JQuery Change Example</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("select").change(function(){
                var selectedOption = $(this).children("option:selected").val();
                $("#message").text("You selected " + selectedOption);
            });
        });
    </script>
</head>
<body>
    <select>
        <option selected disabled>Select an option</option>
        <option value="option1">Option 1</option>
        <option value="option2">Option 2</option>
        <option value="option3">Option 3</option>
    </select>
    <div id="message"></div>
</body>
</html>
Try Playground

In this example, we use $(document).ready() to ensure that the function is executed only after the DOM is fully loaded. Then, we use $("select").change() to register a function that is executed every time the user selects a new option from the drop-down menu. Finally, we update the text of the #message div to display the selected option.

Summary

JQuery change() is a powerful method for creating interactive and dynamic user interfaces. By using it to register a function that is executed whenever the value of an element changes, you can create a wide range of responsive and intuitive applications. Give it a try in your next project!

Published on: