It is necessary to make a conclusion of several selets for further calculation of their values. Problem: displays several times the value of the first select. The answer is preferably in pure javascript.

function calc() { document.getElementById('MB'); var select = document.querySelector('select'); console.log(select.value); document.getElementById('C'); var select = document.querySelector('select'); console.log(select.value); } 
 <select name="P" id="C"> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> </select> <select name="M" id="MB"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> <button type="button" name="button" id="btn" onclick=calc()>BUTTON</button> 

  • 2
    and what exactly does not work? What did you try to do yourself? - Bald
  • @Bald I'm sorry if I'm new. document.getElementById ('id name') var select = document.querySelector ('select') and you can output the value of select.value Question: how to get the value of the second select if getElementById doesn't help? Ie displays two identical values - NoNameCat
  • @Bald <select name = "P" id = "C"> <option value = "4"> 4 </ option> <option value = "5"> 5 </ option> <option value = "6"> 6 </ option> </ select> <select name = "M" id = "MB"> <option value = "1"> 1 </ option> <option value = "2"> 2 </ option> <option value = "3"> 3 </ option> </ select> <button type = "button" name = "button" id = "btn" onclick = calc ()> BUTTON </ button> function calc () {document.getElementById ('MB'); var select = document.querySelector ('select'); console.log (select.value); document.getElementById ('C'); var select = document.querySelector ('select'); console.log (select.value); } - NoNameCat

1 answer 1

In your example, the code did not work, as you expect for the reason that querySelector('select') returns the first matching element from the house . In order for the code to work, you need this code:

 document.getElementById('MB'); var select = document.querySelector('select'); 

replaced by:

 var select = document.getElementById('MB'); 

Getting the selected value from the drop-down list looks like this:

 var selectedValue = select.options[select.selectedIndex].value; 

Working example below

 function calc() { var select = document.getElementById('MB'); console.log(select.options[select.selectedIndex].value); select = document.getElementById('C'); console.log(select.options[select.selectedIndex].value); } 
 <select name="P" id="C"> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> </select> <select name="M" id="MB"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> <button type="button" name="button" id="btn" onclick=calc()>BUTTON</button>