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

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 the 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 its .change() method I will change its 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.

DEMO

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 its 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.

DEMO

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

DEMO

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

DEMO DOWNLOAD

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "WordPress, SEO, jQuery, HTML" and more.