Search code examples
javascriptjqueryjquery-selectorsparentchildren

Parent and child selection, can't access first parent (jquery)


I have a problem with a parent/child selection with jquery.

I have a HTML page who looks like this:

<tr> 
   <input type='checkbox' /> //1st checkbox
   <.. some stuff ../>
</tr>
<tr>
   <td><input type='checkbox' /></td> //2nd checkbox
   <td>
     <select id='stateChanger' onchange='stateChanger();'/>
       <option> ...</option>
       ...
   </td> 
</tr>

I want to check the checkbox of the line I changed with my select at the moment I changed it. But with the code hereinbelow I only check the first checkbox.

function stateChanger(){

        $('#stateChanger').parent().parent().children('td').children("input[type='checkbox']").attr("checked","true");
}

If anyone has idea to help me, I can post the full code. Thanks. Victor


Solution

  • You can use:

    function stateChanger(obj) {
      $(obj).closest("tr").find("td:first input[type='checkbox']").attr("checked", "true")
    }
    

    and add this to onchange='stateChanger();' so it will be onchange='stateChanger(this);'

    This will check the second <input type='checkbox' />

    demo

    function stateChanger(obj) {
      $(obj).closest("tr").find("td:first input[type='checkbox']").attr("checked", "true")
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <table>
      <tr>
        <input type='checkbox' />
      </tr>
      <tr>
        <td><input type='checkbox' /></td>
        <td>
          <select id='stateChanger' onchange='stateChanger(this);' />
          <option> ...</option>
          <option>texst</option>
        </td>
      </tr>
    </table>