How to use jQuery Change Method on textbox, select, radio and checkbox

How to use jQuery Change Method on textbox, select, radio and checkbox

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.

jQuery Select Method Syntax

$(selector).change(function)

Function : It runs when the change method occurs on the selected elements.

Example 1: jQuery Change on Textbox

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");
});
For the change event to occur you have to write something on the textbox then click outside of it. I have used jQuery CSS Method for changing the background color of the textbox.

Example 2: jQuery Change on Select

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");
});
You will love to read my tutorial on jQuery Checkbox Checked that explains all about working with checkboxes using jQuery. Do check it now.

Example 3: jQuery Change on Radio button

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")
}); 

Example 4: jQuery Change on Checkbox

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:

DOWNLOAD

SHARE THIS ARTICLE

  • linkedin
  • reddit
yogihosting

ABOUT THE AUTHOR

I hope you enjoyed reading this tutorial. If it helped you then consider buying a cup of coffee for me. This will help me in writing more such good tutorials for the readers. Thank you. Buy Me A Coffee donate