jQuery change example
The purpose of this example is to show you how to use the jQuery .change()
method.
The users of a dynamic web page make many operations to change HTML elements as the text entering into an input text field, the comboboxes selection, the checkboxes un/checking and so on. To detect these changes and get the changed HTML element’s value, we can use the jQuery .change()
method.
This method can be bonded with any HTML element that will may be changed. As an example, this statement $("input").change(function(){})
will call the anonymous function when the user changes the input field. This method is a shortcut for .on( "change", handler )
.
Let’s look at some examples. To download the jQuery library, click here.
1. HTML
First of all you need to create a simple html document.
<!DOCTYPE html> <html> <head> <title>jQuery Change Example</title> <script src="jquery-2.1.4.min.js"></script> </head> <body> <!-- HTML --> </body> </html>
2. jQuery change examples
2.1 Getting the selected country example
Let’s add the following simple html code.
<select id="country"> <option>United Kingdom</option> <option>Iceland</option> <option>Pakistan</option> <option>Russia</option> <option>India</option> <option>Uzbekistan</option> </select> The selected country is <strong><span id="selectedCountry" />United Kingdom</strong>
In the following jQuery code, the jQuery .change()
method has been used to detect the combobox’s change event.
<script type="text/javascript"> $( "select" ).change(function () { var country = $( "#country option:selected" ).text(); $( "#selectedCountry" ).text(country); }); </script>
The result in the browser would be:
2.2 The user name validation example
Let’s add the following simple html code.
<span id="validation" style="display:none;"> <img src='true.png' id="validationImg" width="25" height="25" /> </span> First Name :<input type="text" class="userInfo"/>
In the following jQuery code, the code at line 2 will add a listener to the changing of the elements that have the “userInfo” class.
<script type="text/javascript"> $( ".userInfo" ).change(function () { var usernameRegex = /^[a-zA-Z0-9]+$/; var username = $(this).val(); var matched = username.match(usernameRegex); if(matched){ $("#validationImg").attr("src","true.png"); } else { $("#validationImg").attr("src","false.png"); } $("#validation").show(); }); </script>
The result in the browser would be:
3.Conclusion
jQuery provides a very simple method that helps us to detect the HTML element changing. The jQuery .change()
method is used for this purpose. This method takes an anonymous function which handles the changing event.