The jQuery Prop method – .prop(), gets or sets the property values of selected elements. These properties can be – border of an element, checkbox checked value, disabled, and so on.
Get the property – It can get a single property value of an element at a time.
Set the property – It can set multiple property values, of multiple elements, at a time.
a. Returning a property value of an element
$(element).prop(property)
b. Set one single property value of one or more elements.
$(selector).prop(property,value)
c. Using function to set one single property value of one or more elements
$(selector).prop(property,function(index,currentvalue))
d. Set multiple property values of one or more elements
$(selector).prop({property:value, property:value,...})
Parameter | Description |
---|---|
property | name of the property. Examples ‘border’, ‘checkbox checked’, ‘disabled’ etc |
value | value of the property |
function(index,currentvalue) | function that returns the attribute value to set them
|
The page has one image with a button.
<img src="animal.jpg" border="10px solid"/>
<button id="button1">Show Width</button>
To get the border of the image I can use .prop() method like this:
$("#button1").click(function (e) {
alert("Width is: " + $("img").prop("border"));
});
The alert message box will show Border is: 10px solid.
Here I have 2 images and a button.
<img src="cat1.jpg" />
<img src="cat2.jpg" />
<button id="button2">Set Border</button>
On the button click event I can set the border of these 2 images to 10px solid width from the jQuery Prop method.
$("#button2").click(function (e) {
$("img").prop("border", "10px solid");
});
So on the button click event the width I am using .prop() to apply border to the images.
To find the checkbox checked property use the .prop() method like below:
<input type="checkbox" /> Checkbox
<button id="button3">Find</button>
$("#button3").click(function (e) {
alert($("input[type='checkbox']").prop("checked"));
});
In the alert box you will get the property value of checkbox.
Consider you have a checkbox and 2 buttons. One button will check the checkbox and the other button will uncheck it.
<input type="checkbox" /> Checkbox
<button id="button4">Click to Check</button>
<button id="button5">Click to Un-Check</button>
To check a checkbox on a button click pass true to the second parameter of .prop() method like shown below:
$("#button4").click(function (e) {
$("input[type='checkbox']").prop("checked", true);
});
To uncheck the checkbox pass false to the second parameter of .prop() method.
$("#button5").click(function (e) {
$("input[type='checkbox']").prop("checked", false);
});
Check the download link: