0

There are two cell in a row and first cell has table and next cell has button. How can i find a button in next cell.

All the buttons in the last cell of each rows has same id, so i need to either find the last cell in the current row or the one next to next to current cell.

I am trying to enable button if any of the checkbox in the current cell is ticked.

<table>
        <tr>
            <td>
                <table>
                    <tr>
                        <td><input id="Checkbox1" type="checkbox" /></td>
                        <td><input id="Checkbox2" type="checkbox" /></td>
                    </tr>
                </table> 
            </td>
            <td><input id="Button1" type="button" value="button" /></td>
        </tr>

        <tr>
            <td>
                <table>
                    <tr>
                        <td><input id="Checkbox1" type="checkbox" /></td>
                        <td><input id="Checkbox2" type="checkbox" /></td>
                    </tr>
                </table> 
            </td>
            <td><input id="Button1" type="button" value="button" /></td>
        </tr>
    </table>
user1263981
  • 2,953
  • 8
  • 57
  • 98
  • IDs must be **unique**. – Ram Apr 21 '15 at 18:29
  • What are the consequences of not doing so? I think there is a difference between whether something SHOULD be unique or MUST be unique (i.e. enforced by web browsers). Should IDs be unique? YES. Must IDs be unique? NO, at least IE and FireFox allow multiple elements to have the same ID. – user1263981 Apr 21 '15 at 18:44
  • http://stackoverflow.com/questions/9454645/does-id-have-to-be-unique-in-the-whole-page – Ram Apr 21 '15 at 18:55
  • Yes, you can use duplicate IDs, if having an invalid document is not a problem you can use as many duplicate IDs as you want. The HTML standard says **MUST**. It's up to you If you want to interpret is as *SHOULD*. – Ram Apr 21 '15 at 19:00

1 Answers1

0

First of all, IDs must be unique in a document otherwise the document is invalid. If you pass an ID selector to jQuery or use the document.getElementById() function only the first matching element is selected.

For getting the input[type=button] element you can traverse up through the ancestors of the checkboxes and select the wrapping td using .closest() method and then select the descendant button of the next cell using .next() and .find() methods:

$('input[type=checkbox]').on('change', function() {
   var button = $(this.parentNode.parentNode)
                    .closest('td')
                    .next()
                    .find('input[type=button]');
});

The above snippet uses this.parentNode.parentNode for selecting the tr grandfather of the checkboxes. The reason is, jQuery closest method starts from testing the current element. $(this).closest('td') returns the td parent and $(this.parentNode) returns the current td itself.

Ram
  • 143,282
  • 16
  • 168
  • 197