Chintan_chiku
Chintan_chiku

Reputation: 425

jquery checkbox inside table tag not able to access

i m trying to access all checkbox inside table tag.... initially all checkbox were inside div tag at that time below code was working fine and i was able to access the each checkbox

   $('#div_id').children('input').each(function()
{
    if(this.type == 'checkbox')
    {
        if($(this).attr('id') == 1)
        {
            this.checked = true;
        }
    }
});

now when i places checkbox inside table it stop working. i tried to change 'div_id' to 'table_id' still no success. any suggestions ?

All checkboxes and table is dynamically created.

Upvotes: 0

Views: 231

Answers (3)

Raja Danish
Raja Danish

Reputation: 235

----------------------------- HTML Code below --------------------------

<table>
    <tr>
        <td><input type="checkbox" checked="checked" /></td>
        <td><input type="checkbox" checked="checked" /></td>
        <td><input type="checkbox" /></td>
        <td><input type="checkbox" /></td>
    </tr>
</table>   

<input type="button" onclick="callFunction()" value="Click" />

-------------------------- JS Code below --------------------------------

<script type="text/javascript">
    function callFunction() {

        $('table input[type=checkbox]').each(function () {
            alert("hi table") //This will be call 4 times.
            if (this.checked) {
                alert("hi inner") ////This will be call 2 times, only for checked checkboxes.
                //this.checked = true;
            }
        });
    }
</script>

Upvotes: 2

Jakob Hohlfeld
Jakob Hohlfeld

Reputation: 1564

You can use selector api:

$('table#id input[type=checkbox]');

will return an array with all checkbox elements.

Upvotes: 0

Chris Dixon
Chris Dixon

Reputation: 9167

.children only travels a single element down the tree (described here https://api.jquery.com/children/).

What you need now is .find, which traverses through all down the child element tree, and thus your code becomes:

$('div_id').find('input').each(function()
{
    if(this.type == 'checkbox')
    {
        if($(this).attr('id') == 1)
        {
            this.checked = true;
        }
    }
});

Upvotes: 2

Related Questions