akshay talathi akshay talathi - 7 months ago 13
Javascript Question

How to get option value of only the selected checkboxes?

I want to get option value of only selected checkbox, but I am getting value from all the checkboxes.

My HTML code:

<div class= "outer">
<div class="inner" id="inner">
<input type="checkbox" name="machine" value="plane">BBQ Sauce<br>
<select class="weight" name="m2" id="m2">
<option value="1">Light</option>
<option value="2">Normal</option>
<option value="3">Extra</option>
</select>

</div>
<div class="inner" id="inner">
<input type="checkbox" name="machine" value="plane"> Alfredo Sauce<br>
<select class="weight" name="m2" id="m2">
<option value="1">Light</option>
<option value="2">Normal</option>
<option value="3">Extra</option>
</select>
</div>
</div>
<input type="submit" value="Submit">


My JavaScript code:

function myAction(){
var vals = [];
var machine = document.getElementsByName('machine');

var m2 = document.getElementById('m2');

for(var i=0, n= machine.length; i<n; i++){
if(machine[i].checked){
vals.push(m2.value);
}
}
}

Answer

IDs must be unique.

Instead, you could use querySelectorAll() on the existing weight classes to grab only the select elements that follow a checked input (using the general sibling selector):

document.querySelectorAll('input:checked ~ .weight')

The select element values will be the same as their selected options' values.

Snippet

document.querySelector('input[type=submit]').addEventListener('click', myAction);

function myAction() {
  var vals = [],  //no need for new Array()
      weights= document.querySelectorAll('input:checked ~ .weight');
  
  for(var i = 0 ; i < weights.length ; i++) {
    vals.push(weights[i].value);
  }
  
  console.log(vals);
}
<div class="outer">
  <div class="inner" id="inner">
    <input type="checkbox" name="machine" value="plane">I have a plane
    <br>
    <select class="weight" name="m2">
      <option value="1">Light</option>
      <option value="2">Normal</option>
      <option value="3">Extra</option>
    </select>

  </div>
  <div class="inner" id="inner">
    <input type="checkbox" name="machine" value="plane">I have 2 planes
    <br>
    <select class="weight" name="m2">
      <option value="1">Light</option>
      <option value="2">Normal</option>
      <option value="3">Extra</option>
    </select>
  </div>
</div>
<input type="submit" value="Submit">