checked by name and value javascript

Asked

Viewed 372 times

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>

  • 1

    How so check up on a radio input?

  • leaves the radio checked = true;

1 answer

0


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>

  • Wow... I hadn’t even seen

  • Thank you very much.

  • 1

    @lucaspereira I edited the answer with a simpler suggestion, if you decided to please mark the answer as correct, if you do not know how to see this little turotial of how to use the site: https://pt.meta.stackoverflow.com/q/1078/3635 - Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.