The jQuery Change method occurs when the value of the element changes. It can be applied to textbox, select, textarea, radio button and checkbox.
Note – For textbox the change method occurs when its content is changed and it loses focus. For select, checkbox, radio controls, the change method occurs when any option is selected or changed.
$(selector).change(function)
Function : It runs when the change method occurs on the selected elements.
I have an input control of type text (textbox). On it’s .change() method I will change the background color to purple.
This code is given below:
<input type="text" id="nameInput" />
$("#nameInput").change(function () {
$(this).css("background-color", "purple");
});
I now have a country select control. I have applied jQuery Change method on it and this will change it’s background color when a country is selected.
<select id="countrySelect">
<option value="Select">Select</option>
<option value="India">India</option>
<option value="China">China</option>
<option value="USA">USA</option>
<option value="UK">UK</option>
</select>
$("#countrySelect").change(function () {
$(this).css("background-color", "purple");
});
Now I am applying the .change() method on 2 radio buttons. Whenever a radio button is selected I will get an alert message.
<input type="radio" name="gender" id="maleRadio" />Male
<input type="radio" name="gender" id="femaleRadio" />Female
$("#maleRadio").change(function () {
alert("Male is checked")
});
$("#femaleRadio").change(function () {
alert("Female is checked")
});
The .change() method can also be applied on checkboxes. See the below code with does this thing.
<input type="checkbox" id="agreeCheckbox" /> Agree to our policies
$("#agreeCheckbox").change(function () {
alert($(this).prop("checked"))
});
DOWNLOAD: