Skip to content
Advertisement

Getting next element in a table javascript

https://jsfiddle.net/en6jh7pa/1/

I am having issues grabbing the next element, it is returning null for the next element.

I am passing “this? as onclick and I assumed that you could use this to grab the next element but it seems that it instead returns null

Thanks for your help

    function assignnames(checkboxelement){
    
    checkboxelement.setAttribute("name", "checkbox");
    var value1box = checkboxelement.nextSibling;
    value1box.setAttribute("name", "notnull");
    var value2box = checkboxelement.nextElementSibling;
    value2box.setAttribute("name", "notnull");
    alert("done");
    
    }
    <table border="1">
    <tr>
      <th>
        Checkbox
      </th>
      <th>
        value1
      </th>
      <th>
        value2
      </th>
    </tr>
    <tr>
      <td>
    <input type="checkbox" onclick="assignnames(this)" id="checkbox1"/>
      </td>
      <td>
         <input type="text" name="" id="fname1">
      </td>
      <td>
      <input type="text" name="" id="lname1">
      </td>
    </tr>
    </table>

Advertisement

Answer

If you want to get the text inputs in the same row, you can go up to the row, then use a selector to get the inputs, e.g.

function getParent(node, tag) {
  var tag = tag.toLowerCase();
  do {
    if (node.tagName.toLowerCase() == tag) {
      return node;
    }
    node = node.parentNode;
  } while (node && node.tagName && node.parentNode)
  return null;
}

function getInputs(evt) {
  var row = getParent(this, 'tr');
  var inputs;
  if (row) {
    inputs = row.querySelectorAll('input[type="text"]');
  }
  console.log(`Found ${inputs.length} text inputs, node is ${this.checked? '':'not '}checked.`);
}

window.onload = function(){
  document.getElementById('checkbox1').addEventListener('click', getInputs, false);
};
<table border="1">
  <tr><th>Checkbox
      <th>value1
      <th>value2
  <tr><td><input type="checkbox" id="checkbox1">
      <td><input type="text" name="" id="fname1">
      <td><input type="text" name="" id="lname1">
</table>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement