I'm sure I'm going to lose some rep points for this, because it's such a basic question, but I can't figure out what I'm doing wrong with jQuery selectors using "#" to select by id.
given this element in my document:
<%= Html.CheckBox("IsAlwaysValid", true,
new { onchange = "showHideValidSetList()", id = "IsAlwaysValidCheckBox" })%>
(which outputs the following markup:
<input checked="checked" id="IsAlwaysValidCheckBox" name="IsAlwaysValid" onchange="showHideValidSetList()" type="checkbox" value="true" /><input name="IsAlwaysValid" type="hidden" value="false" />
)
Then this function using a jQuery selector:
<script type="text/javascript">
function showHideValidSetList() {
if ($("#IsAlwaysValidCheckBox").checked) {
alert("IsAlwaysValidCheckBox is checked");
return;
}
else {
alert("IsAlwaysValidCheckBox is NOT checked");
return;
}
}
</script>
should be exactly equivalent to this one using the javascript DOM:
<script type="text/javascript">
function showHideValidSetList() {
if (document.getElementById("IsAlwaysValidCheckBox").checked) {
alert("IsAlwaysValidCheckBox is checked");
return;
}
else {
alert("IsAlwaysValidCheckBox is NOT checked");
return;
}
}
</script>
Right? But the javascript version works as expected, while the jQuery one always takes the "else" branch, showing that it's not really looking at the state of the checkbox.
What am I doing wrong?
Thanks for bearing with me.
Use this:
if ($(checkBoxControl).attr("checked")) {
instead of this:
if ($("#IsAlwaysValidCheckBox").checked) {
Though it looks like jQuery selectors return DOM elements (like checkboxes), they really return a jQuery object, which does not have a method called checked. You can see this most clearly in the uncompressed jquery source code (from the current release, version 1.3.2):
jQuery.fn = jQuery.prototype = {
init: function( selector, context ) {
// ...
// Handle $(DOMElement)
if ( selector.nodeType ) {
this[0] = selector;
this.length = 1;
this.context = selector;
return this;
}
// ...
}
}
Many of the interesting jQuery methods (like animate, attr, html, etc.) operate on this.context, which is specified or redefined whenever you apply a selector.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With