w3resource
jquery exercises

jQuery: Display the checked attribute and property of a checkbox as it changes

jQuery Fundamental - I : Exercise-27

Using jQuery display the checked attribute and property of a checkbox as it changes.

<body>
<input id="check1" type="checkbox" checked="checked">
<label for="check1">Check me</label>
</body>

Sample solution :

HTML Code :

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-git.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Using jQuery display the checked attribute and property of a checkbox as it changes.</title>
</head>
<body>
<input id="check1" type="checkbox" checked="checked">
<label for="check1">Check me</label>
</body>
</html>

JavaScript Code :

$( "input" )
  .change(function() {
    var $input = $( this );
   console.log(".attr( 'checked' )");
   console.log(".prop( 'checked' ): " +$input.prop( "checked" ))    ;       
console.log(".is( ':checked' ): " + $input.is( ":checked" ) );               
  })
  .change();

Used Methods :

  • .attr() : Get the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element.
  • .prop() : Get the value of a property for the first element in the set of matched elements or set one or more properties for every matched element.
  • .change() : Bind an event handler to the “change” JavaScript event, or trigger that event on an element.

See the Pen jquery-fundamental-exercise-27 by w3resource (@w3resource) on CodePen.


Contribute your code and comments through Disqus.

Previous: Using jQuery append all spans to the element with specified id.
Next: Find the title attribute of the first in the page.

What is the difficulty level of this exercise?



New Content: Composer: Dependency manager for PHP, R Programming