Get content from text fields via ID using JavaScript

2

I have a checkbox that at the time I select and search for the value in the type="text" field, one of the fields is working perfectly plus the second field does not work.

function pega(){
	var opcao = document.getElementById("opcao");
	var numero1 = document.getElementById("number1").value;
	var numero2 = document.getElementById("number2").value;

	if (opcao.checked == true){
		document.getElementById("total").innerHTML = numero1;
	}
  /*

	if (opcao.checked == true){
		document.getElementById("total").innerHTML = numero2;
	}*/

}
<input type="checkbox" id="opcao" name="Pacote" value="primeira opcao" onclick ="pega()">
<input type="text" id="number1" />

<input type="checkbox" id="opcao" name="Pacote" value="primeira opcao" onclick ="pega()">
<input type="text" id="number2" />
<div id="total"></div>

My idea then is to calculate the two fields, but do I need to know if this way I'm going to do it?

    
asked by anonymous 01.12.2015 / 21:51

2 answers

6

In HTML the IDs must be unique. To group elements use classes ( class ) and to identify uniquely use id .

So the problem with your code is that .getElementById("opcao") will only return an element, the first thing it finds.

You can correct this by giving different IDs, or you can use the fact that when the pega function can receive the argument event which is the event that triggers this onclick . And, there, the .target property that tells you which element the clicked. Thus opção = e.target;

Another option is to do so, which reads the values of all checkbox regardless of how many:

var opcoes = document.querySelectorAll('input[type="checkbox"]');
var inputs = document.querySelectorAll('input[type="text"]');

function lerValores(els) {
  return [].map.call(els, function (el) {
    return el.checked;
  });

}

function pega(e) {
  var total = 0;
  lerValores(opcoes).forEach(function (checked, i) {
    if (checked) total += parseInt(inputs[i].value, 10);;
  });
  document.getElementById("total").innerHTML = total;
}

Example: link

    
01.12.2015 / 22:46
0

I believe that what you want is this:

function pega(){
    if (document.getElementById("opcao1").checked == true) {
        document.getElementById("total").innerHTML = document.getElementById('number1').value;
      }
    if (document.getElementById("opcao2").checked == true) {
        document.getElementById("total").innerHTML = document.getElementById('number2').value;;
      }
    
}
<input type="checkbox" id="opcao1" name="pacote1" value="number1" onclick ="pega()">
<input type="text" id="number1" />

<input type="checkbox" id="opcao2" name="pacote2" value="number2" onclick ="pega()">
<input type="text" id="number2" />

<div id="total"></div>
    
01.12.2015 / 22:17