Wednesday, February 6, 2013

How to set one or more properties for the set of matched elements using jQuery?

To set one or more properties for the set of matched elements, we can make use of the ".prop(propertyName,value)" method in jQuery. Where "propertyName" is the name of the property to set and "value" is the value of the property to be set.

Using ".prop(propertyName,value)" method to set the value of properties is the most convenient way, especially while setting multiple properties.

Note: Properties generally affect the dynamic state of a DOM element without changing the serialized HTML attribute.

Set the value of a property using ".prop(propertyName, value)" method:

$(document).ready(function(){
$("#checkAll").click(function(){
$("input[type='checkbox']").prop("checked", true)
});
$("#unCheckAll").click(function(){
$("input[type='checkbox']").prop("checked", false)
});
$("#toggleAll").click(function(){
$("input[type='checkbox']").prop("checked", function( i, val ) {
  return !val;
});
});
});

Example:

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
$("#checkAll").click(function(){
$("input[type='checkbox']").prop("checked", true)
});
$("#unCheckAll").click(function(){
$("input[type='checkbox']").prop("checked", false)
});
$("#toggleAll").click(function(){
$("input[type='checkbox']").prop("checked", function( i, val ) {
  return !val;
});
});
});
</script>
</head>
<body>
<b>Click on the below buttons to see the usage of ".prop" method:</b><br/>
<input type="button" id="checkAll" value="Check all">
<input type="button" id="unCheckAll" value="Uncheck all">
<input type="button" id="toggleAll" value="Toggle all"></br></br>
<input id="checkbox1" type="checkbox" checked="checked"><label for="checkbox1">Check/Uncheck me</label></br></br>
<input id="checkbox2" type="checkbox" ><label for="checkbox2">Check/Uncheck me</label></br></br>
<input id="checkbox3" type="checkbox" checked="checked"><label for="checkbox3">Check/Uncheck me</label></br></br>
<input id="checkbox4" type="checkbox" ><label for="checkbox4">Check/Uncheck me</label></br></br>
<div></div>
</body>
</html>

Sample Output:


How to set one or more properties for the set of matched elements using jQuery

Demo:



0 comments:

Post a Comment

Subscribe via Email