Introduction to JQUERY - Listening to Change Events using the change() method.

Guest Posts Paolo Nikko Nuñal

There are times that we want listen for events that changes most especially those found on the input fields. In this tutorial we are going to tackle about the change() method and how it is very useful when it comes to listening for any change on your input fields as well as drop downs.

Syntax:

$(selector).change(HANDLER)

HANDLER(EVENT OBJECT) - a function to be execute when the event is triggered.

Code


<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
      $("#name_field").change(function(){
         alert("Value has been changed to: "+$(this).val());
      });
});
</script>
</head>
<body>
<input type="text" id="name_field"> Write Something here.
</body>
</html>


The change event occurs when there is something change on the field. In our example above, every time you enter something on the text field, an alert message will be displayed stating that there has been changes been made. The reason of which is that the input box has a default value of null. And when you input something on the field, this triggered the change() method since the original value was null and was changed to the inputted text that you have made.

The change() method is not limited to text field but also applicable to drop downs as well. See example below for more information.

Code


<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
       $("#dropdown").change(function(){
         alert("Value has been changed to: "+$(this).val());
      });
});
</script>
</head>
<body>
<select id="dropdown">
<option></option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
Select from the options using the dropdown.
</body>
</html>