checked radio by name and value javascript

0

I need to mark one of the radio inputs with checked via javascript, preferably using name and / or value for 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()">Try it</button>


<script>
function myFunction() {
    var lis = document.getElementByName("generoi1");
    lis.length;
    lis[0].checked = true;
}
</script>

</body>
</html>
    
asked by anonymous 15.07.2018 / 00:48

1 answer

0

This is a typo, there is no getElementByName , an S is missing, the 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 get the first element it finds and lis[1] will get the second and so on because the index starts from zero.

You can choose to use querySelector which is similar to CSS selectors (if you already know), 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>
    
15.07.2018 / 00:54