Get the value of a radio button with Vanilla Javascript?

1

How to select a radio button using pure JS and pick up the user-defined value?

Follow my HTML:

<div class="form-check form-check-inline">
    <input class="form-check-input" type="radio" name="cadastro" id="professorCadastro" value="professor">
    <label class="form-check-label" for="professorCadastro">Professor</label>
</div>
<div class="form-check form-check-inline">
    <input class="form-check-input" type="radio" name="cadastro" id="alunoCadastro" value="aluno">
    <label class="form-check-label" for="alunoCadastro">Aluno</label>
</div>
<div class="form-check form-check-inline">
     <input class="form-check-input" type="radio" name="cadastro" id="empresaCadastro" value="empresa" disabled>
     <label class="form-check-label" for="empresaCadastro">Empresa</label>
</div>


Follow me JS so far

let tipoCadastro = document.getElementsByName('cadastro')
    
asked by anonymous 16.05.2018 / 16:49

2 answers

1

To get value from a collection of radio button , you can create a click event for each and get its value by clicking on it:

// pego todos os radios com name=cadastro
var radios = document.querySelectorAll("input[type='radio'][name='cadastro']");
for(var x=0; x<radios.length; x++){
   radios[x].addEventListener("click", function(){
      var valor = this.value;
      console.log(valor);
   });
}
<div class="form-check form-check-inline">
    <input class="form-check-input" type="radio" name="cadastro" id="professorCadastro" value="professor">
    <label class="form-check-label" for="professorCadastro">Professor</label>
</div>
<div class="form-check form-check-inline">
    <input class="form-check-input" type="radio" name="cadastro" id="alunoCadastro" value="aluno">
    <label class="form-check-label" for="alunoCadastro">Aluno</label>
</div>
<div class="form-check form-check-inline">
     <input class="form-check-input" type="radio" name="cadastro" id="empresaCadastro" value="empresa" disabled>
     <label class="form-check-label" for="empresaCadastro">Empresa</label>
</div>
    
16.05.2018 / 17:25
1

The getElementsByName function returns a NodeList , which is as was an array of elements with that name. This causes you to have access to the first one, in the 0 position or alternatively to use a loop / cycle to cycle through the various elements and do something with them.

Assuming you only have one element with that name, you can access the value with:

let valor = document.getElementsByName('cadastro')[0].value;
//                                                 ^ ---- primeiro

However, if you already have id in the element, simplify and use getElementById , which is no longer the case, since it only takes one element, since id must be unique.

    
16.05.2018 / 17:10