Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I can't figure this one out. According to W3 Schools, the checked property sets or returns the checked state of a checkbox.

So why does $('input').checked ? $('div').slideDown() : $('div').slideUp(); not work?

Using prop however, does work.

$('input').prop('checked') ? $('div').slideDown() : $('div').slideUp();

This is for a checkbox that is checked based on a database value.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
336 views
Welcome To Ask or Share your Answers For Others

1 Answer

checked is a DOM element property so use it on DOM elements instead of jQuery objects.

$('input')[0].checked

if you have a jQuery object, use prop instead of attr since you are checking a property. Just as a reference:

$("<input type='checkbox' checked='checked'>").attr("checked") // "checked"
$("<input type='checkbox' checked='foo'>").attr("checked") // "checked"
$("<input type='checkbox' checked>").attr("checked") // "checked"
$("<input type='checkbox'>").attr("checked") // undefined

Whereas [0].getAttribute("checked") will return the actual value.

prop will return true or false based on whether or not the attribute exists at all


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...