Tuesday, February 5, 2013

How to get the value of a property for the first matched element using jQuery?

To calculate the value of an property for the first matched we can make use of the ".prop()" method in jQuery.

With the help of ".prop()" method we can calculate the value of the property only for first matched element. In order to calculate the property value for each element individually, we should use a looping construct like ".each()" or ".map()" method of jQuery.

Note: If the properties are not set on the elements, then the ".prop()" method will return "undefined".

Here we need to understand the difference between ".attr()" and ".prop" methods of jQuery. Below is a sample value which we get, when we use the methods ".attr()" and ".prop" on a "checked" attribute of a checkbox.

         for the code ".attr('checked')" output is "checked".
         for the code ".prop('checked')" output is "true".

Get the value of a property using ".prop()" method:

$(document).ready(function(){
$("input").change(function() {
  var checkProperty = $(this);
  $("div").html(".attr('checked'): <b>" + checkProperty.attr('checked') + "</b><br>"
              + ".prop('checked'): <b>" + checkProperty.prop('checked')) + "</b><br>";
}).change();
});

Example:

<!DOCTYPE html>
<html>
<head>
<style>     
 body {background:#F1F1A8;} 
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
$("input").change(function() {
  var checkProperty = $(this);
  $("div").html(".attr('checked'): <b>" + checkProperty.attr('checked') + "</b><br>"
              + ".prop('checked'): <b>" + checkProperty.prop('checked')) + "</b><br>";
}).change();
});
</script>
</head>
<body>
<b>Click on the below checkbox to see the usage of ".attr()" and ".prop" methods:</b><br/>
<input id="checkbox1" type="checkbox" checked="checked">
<label for="checkbox1">Check/Uncheck me</label></br></br>
<div></div>
</body>
</html>

Sample Output:


How to get the value of a property for the first matched element using jQuery

Demo:



0 comments:

Post a Comment

Subscribe via Email