Validation of sex with input radio is giving error?

-1

I created two fields input radio for sex and put value="m" and the other value="f" . I left default as input with value="m" checked (so that at startup it's checked), but when I send to JS, even if I set input value="f" , it returns me "m" guilty of checked

input checked is in the way, but I do not want to take it out.

This is my verification code for input radio "sex". Each input has a class() with the same name. I gave one

querySelectorAll();

and I played it in the sexo variable. The idea is: if the first input (((sexo[0]))) is checked, then it is m , otherwise it is f .

if(sexo[0].checked){
    sexo1 = "m"
}else{
    sexo1 = "f";
}
    
asked by anonymous 20.12.2017 / 14:51

2 answers

1

Here is a working example I created, can build on and modify your code.

$('button').click(function(){
  console.log($('input[type=radio]:checked').val());  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="radio" name="sexo" value="M" checked>M</input>
<br>
<input type="radio" name="sexo" value="F" >F</input>
<br>
<button>Checar Valor</button>
    
20.12.2017 / 15:46
0

inputs of type radio of the same collection should have the same name so you can choose one or the other:

<input class="sexo" name="sexo" type="radio" value="m" checked="checked" /> masculino
<br />
<input class="sexo" name="sexo" type="radio" value="f" /> feminino

It's okay to leave the first one marked with checked because JavaScript will normally detect which one is checked:

function checa(){
   var sexo = document.querySelectorAll('.sexo');
   
   if(sexo[0].checked){
      sexo1 = "m";
   }else{
      sexo1 = "f";
   }
   alert(sexo1);
}
<input class="sexo" name="sexo" type="radio" value="m" checked="checked" /> masculino
<br />
<input class="sexo" name="sexo" type="radio" value="f" /> feminino
<br />
<br />
<input type="button" value="Verificar sexo" onclick="checa()" />
    
20.12.2017 / 16:11