Syntax of .prop() to Return (or Get)
$(selector).prop(property)
Syntax of .prop() to Set
Use the below syntax when you want to change or set the property or value of an element.
$(selector).prop(property, value)
The jQuery .prop() method can be used on a variety of elements. Here in this post, I am sharing two examples explaining how to use the prop() method on checkboxes and radio button.
Note: The .prop() method was introduced for the first time in jQuery 1.6.
Using .prop() with Checkboxes
You can easily set the properties and values of multiple checkboxes dynamically using the prop() method.
<!DOCTYPE html> <html> <head> <title>Using .prop() with Checkboxes</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </head> <body> <div> <input type="checkbox" id="chk1" /><label>Pen</label> <br /> <input type="checkbox" id="chk2" /><label>Eraser</label> <br /> <input type="checkbox" id="chk3" /><label>Pencil</label> </div> <p> <input type="checkbox" id="chkAll" /><label id="lbl">Check All</label> </p> </body> <script> $(document).ready(function () { $('#chkAll').click(function () { if ($(this).is(':checked')) { $('div [id*=chk]').prop('checked', true); // Set property as checked. } else { $('div [id*=chk]').prop('checked', false); } $('#lbl').html($(this).is(':checked') ? 'Un-Check All' : 'Check All'); }); }); </script> </html>
In the above code, I am checking and un-checking a group of checkboxes instantly and dynamically using the .prop() method. The method took a Boolean parameter, true or false. True, when I want set the property value as checked. False, when I want set the property value as un-checked.
Interestingly, you can replace the if else condition in the above code, with a single line code, like this.
$('div [id*=chk]').prop('checked', $(this).is(':checked'));
This will work since the second parameter in the prop() method needs a Boolean value and the statement $(this).is(':checked') returns a true or false.
Using .prop() with Radio Button
Here’s another interesting example, where I have used the .prop() to get and set property values of a radio button.
<!DOCTYPE html> <html> <head> <title>Using .prop() with Radio Button</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </head> <body> <div> <input type="radio" name="games" value="hockey" /> Playing Hockey </div> <p> <input type="button" value="Submit" id="submit" /> </p> </body> <script> $(document).ready(function () { $('input[type=button]').click(function () { $('div [name=games]').prop('checked', true); setTimeout(unCheckRadio, 3000); // Uncheck the radio button after 3000 milliseconds. }); let unCheckRadio = () => { $('div [name=games]').prop('checked', false); } }); </script> </html>
Clicking the submit button will temporarily set the radio as checked. Assuming a game has just started. After few seconds (change is minutes or hours), I am un-checking the radio again using the .prop() method.