jQuery change()

The jQuery change() method is used to attach a function to run when a change event occurs i.e, when the value of an element is changed. This method is limited for form fields only, for input elements, textarea boxes and select elements.

  • The change event is fired immediately in case of select boxes, checkboxes, and radio buttons, as soon as the user makes a selection.
  • For elements of other types, the change event occurs as soon as the field loses focus.

Syntax:

To trigger the change event for selected elements.

$(selector).change() 

To add a function to the change event.

$(selector).change(function)  

Function:

  • It is an optional parameter.
  • The function parameter specifies the function to run when the event occurs.

 

Example 1

<!DOCTYPE html>
<html>
 
<head>  
<style>    
  div {    
	color: turquoise;    
  }    
  </style>    
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>    
</head>    
<body>    
 <select id="me" name="food" >    
  <option>Rice</option>    
  <option selected="selected">Wheat</option>    
  <option>Pulses</option>    
  <option>Vegetables</option>    
  <option>Fruits</option>    
  <option>Dry fruits</option>    
</select>    
<div id="loc"></div>    
 <script>    
$( "select" ) .change(function () {    
document.getElementById("loc").innerHTML="You selected: "+document.getElementById("me").value;  
});  
</script>    
 </body>    
</html>

Try it

JS Bin on jsbin.com

Example 2

<!DOCTYPE html>
<html>
 
<head>  
<style>    
  div {    
	color: turquoise;    
  }    
  </style>    
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>    
</head>    
<body>    
<select name="Food" multiple="multiple">  
  <option>Wheat</option>  
  <option selected="selected">Rice</option>  
  <option>Pulses</option>  
  <option selected="selected">Fruits</option>  
  <option>Vegetables</option>  
  <option>Dry Fruits</option>  
</select>  
<div></div>  
 <script>  
$( "select" )  
  .change(function () {  
	var str = "";  
	$( "select option:selected" ).each(function() {  
  	str += $( this ).text() + " ";  
	});  
	$( "div" ).text( str );  
  })  
  .change();  
</script>  
 </body>  
</html>

Try it

JS Bin on jsbin.com

Please Share