开发者

Jquery find a checkbox inside a table row

My html

<TR class="datarow" id="rowId"><TD>1</TD><TD>895171</TD><td class="classID"><INPUT type="checkbox" /></TD></TR>

how do I use Jquery to find out whether the checkbox in this particular row is checked or not. Assume that i know the unique rowId.

Currently, I am doing this

var checkbox = $('#' + rowId + " td input:checkbox");

        if (checkbox.checked) {
           alert("checked");
        } else {
           alert("unchecked");
        }

But this doesn't seem to detect when the checkbox is checked.

EDITED Curiously, the following didn't work either:

   开发者_如何学Python     var curRow = $('#' + curRowId);
        var checkbox = $(curRow).find('input:checkbox').eq(0);



        if (checkbox.checked) {
           alert("checked");

        } else {
           alert("unchecked");

        }


You can do this:

var isChecked = $("#rowId input:checkbox")[0].checked;

That uses a descendant selector for the checkbox, then gets the raw DOM element, and looks at its checked property.

References for selectors:

  • Selectors supported by most browsers: CSS 2.1
  • Newer selectors supported by some browsers and by various JavaScript libraries (for interacting with the DOM): CSS3 Selectors


Updated:

var rowId = "";
var checked = $("#" + rowId + " input:checkbox")[0].checked;

Your original code does not work because you're calling checked on a jQuery result set. You need to get out the actual DOM element, which you can do by calling get() (Or by indexing the object directly like in T.J.'s answer). Since there's only one result, you want the element at index 0 in the result set.

Edit after seeing updated code in OP:

Using eq() reduces the matched elements to the one at the specified index. Effectively this will return a jQuery result set with one matched object--the one you requested at the specified index. It still doesn't return a DOM element, which you need to use the checked property.


If you only have one checkbox per row this is the quickest way

!!$('#rowId input:checked').length

You can also omit the !! and check against '>0' but I think the !! is actually faster


This would do it

var checked = $("#rowId" + rowId + " td.classID input:checkbox").is(":checked");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜