This is typo, there is no getElementByName
, missing an S, correct is getElementsByName
:
<!DOCTYPE html>
<html>
<body>
<input type="radio" name="generoi1" value="female">Feminino<br>
<input type="radio" name="generoi1" value="male">Masculino<br>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var lis = document.getElementsByName("generoi1");
lis.length;
lis[0].checked = true;
}
</script>
</body>
</html>
The lis[0]
will take the first element you find and lis[1]
will take the second and so on, as the Dice starts from scratch.
You can choose to use querySelector
which is similar to CSS selectors (if you already know how to use), which should look like this:
<!DOCTYPE html>
<html>
<body>
<input type="radio" name="generoi1" value="female">Feminino<br>
<input type="radio" name="generoi1" value="male">Masculino<br>
<button onclick="myFunction('female')">Feminino</button>
<button onclick="myFunction('male')">Masculino</button>
<script>
function myFunction(tipo) {
var escolhido = document.querySelector("input[name=generoi1][value=" + tipo + "]");
if (escolhido) {
escolhido.checked = true;
} else {
alert('Elemento não encontrado');
}
}
</script>
</body>
</html>
How so check up on a radio input?
– LeAndrade
leaves the radio checked = true;
– lucas pereira