The Jquery attr method returns undefined for a checked check box

advertisements

For the above checkbox

document.getElementById("checkbox1").checked // -> returns true

But

var byAppr = document.getElementById('checkbox1').value;
$(byAppr).attr('checked') // -> returns undefined

I am testing this in firefox 3.6


Use one of the following:

  • $('#checkbox1').prop('checked') - in jQuery 1.6+, usually the way to go
  • $('#checkbox1').is(':checked') - all jQuery versions, but slower
  • $('#checkbox1').attr('checked') - NOT in jQuery 1.6 - but in 1.6.1 and <=1.5, don't use it

Also, in cases where you already have the DOM element available directly (e.g. this in an event handler bound to the field), use this.checked instead of $(this) with one of the methods above!