Home > Mobile >  How to get adjacent col value in a div-table using js?
How to get adjacent col value in a div-table using js?

Time:01-21

I have an html table, which is structured like this:

<body>
<div  id="sidebar-record-block">
<div >
  <div >Sel</div>
  <div >Color</div>
  <div >Hex</div>
</div>
<div id="field-0000" >
  <input type="checkbox"  name="checkBox" id="cbfield-0000">
  <div >yellow</div>
  <div ></div>
</div>
  <div id="field-0001" >
    <input type="checkbox"  name="checkBox" id="cbfield-0001">
    <div >red</div>
  <div ></div>
</div>
</body>

I can iterate over the checkboxes using the code below and push the checked rows into an array:

saveButton.onclick = function(){
   var checkedRowIndexes = []; 
  var selectedColors = []; 
  var checkedRows = document.querySelectorAll("input[type='checkbox']");
  for (var i = 0; i < checkedRows.length; i  ){
    if (checkedRows[i].checked){
    checkedRowIndexes.push(i);
    }
  }
  console.log(checkedRowIndexes);
}

But how would I go about iterating over the table and push the color (2º col) instead, using javascript?

Thank you!

CodePudding user response:

var checkedRowIndexes = [];
var selectedColors = [];
var checkedRows = document.querySelectorAll("input[type='checkbox']");

for (var i = 0; i < checkedRows.length; i  ) {
  if (checkedRows[i].checked) {    
    checkedRowIndexes.push(i);
    selectedColors.push(checkedRows[i].nextElementSibling.innerText);
  }
}
console.log(checkedRowIndexes, selectedColors);
<div  id="sidebar-record-block">
  <div >
    <div >Sel</div>
    <div >Color</div>
    <div >Hex</div>
  </div>
  <div id="field-0000" >
    <input type="checkbox"  name="checkBox" id="cbfield-0000">
    <div >yellow</div>
    <div ></div>
  </div>
  <div id="field-0001" >
    <input type="checkbox"  name="checkBox" id="cbfield-0001">
    <div >red</div>
    <div ></div>
  </div>

  •  Tags:  
  • Related