jQuery | change() with Examples

The change() is an inbuilt method in jQuery that is used to change the value of the input fields. This method is worked only on the “input, textarea and select” elements.

Syntax :

$(selector).change(function)

Parameter: It accepts an optional parameter “function”.
Return Value: It returns the element with the modification.
jQuery code to show the working of change() method:
Code #1:
In the below code, no function is passed to the change method.

filter_none

edit
close

play_arrow

link
brightness_4
code

<html>
  
<head>
               jquery/3.3.1/jquery.min.js"></script>
    <!--Demo of change method without passing function-->
    <script>
        $(document).ready(function() {
            $("button").click(function() {
                $("input").change();
            });
        });
    </script>
</head>
  
<body>
    <p>Click the button to see the changed value !!!</p>
    <!--click on this button and see the change -->
    <button>Click Me!</button>
    <p>Enter value:
        <input value="Donald" onchange="alert(this.value)"
        type="text"></p>
</body>
  
</html>

chevron_right


Output:
Before clicking the “Click Me” button-

After clicking the “Click Me” button-

Code #2:
In the below code, function is passed to the change method.

filter_none

edit
close

play_arrow

link
brightness_4
code

<html>
  
<head>
                  jquery/3.3.1/jquery.min.js"></script>
    <!--Here function is passed to the change method-->
    <script>
        $(document).ready(function() {
            $(".field").change(function() {
                $(this).css("background-color", "#7FFF00");
            });
        });
    </script>
    <style>
        .field {
            padding: 5px;
        }
    </style>
</head>
  
<body>
    <!--write something and click outside -->
    Enter Value:
    <input class="field" type="text">
    <p>Write something in the input field, and then
        press enter or click outside the field.</p>
</body>
  
</html>

chevron_right


Output:
Before entering any values to the “Enter Value:” box-

After entering a values of “GeeksforGeeks” to the “Enter Value:” box and clicking outside of the box-



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.