Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery basic help

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.

like image 811
Dave Hanna Avatar asked Mar 12 '26 12:03

Dave Hanna


1 Answers

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.

like image 169
Jeff Sternal Avatar answered Mar 15 '26 15:03

Jeff Sternal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!