Kaddy
Kaddy

Reputation: 1266

Jquery attr method returns undefined for a checked checkbox

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

Upvotes: 21

Views: 28284

Answers (2)

ThiefMaster
ThiefMaster

Reputation: 318518

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!

Upvotes: 75

glortho
glortho

Reputation: 13200

You're selecting based on value. I think you want:

var byAppr = document.getElementById('checkbox1');
$(byAppr).attr('checked')

Upvotes: 2

Related Questions