Open link from a checkbox using Javascript

Asked

Viewed 571 times

0

I need to open a link in the same tab from a checkbox, where I will pass parameters.

This is the HTML:

<div class="prog">
    <legend class="">Genero</legend>
    <form action="#">
        <input type="checkbox" name="genero" value="acao"> Ação<br>
        <input type="checkbox" name="genero" value="aventura" > Aventura<br>
        <input type="checkbox" name="genero" value="esportes" > Esportes<br>
        <input type="checkbox" name="genero" value="rpg" > RPG<br>
        <input type="checkbox" name="genero" value="arcade" > Arcade<br>
    </form>
</div>

In each one I will pass a parameter to search the database, but I do not know the command in Javascript.

1 answer

2

The code below submits the form when any checkbox is marked.

DEMO

<div class="prog">
    <legend class="">Genero</legend>
    <form action="" method="post">
        <input type="checkbox" name="genero" value="acao" onclick="this.form.submit();"> Ação<br>
        <input type="checkbox" name="genero" value="aventura" onclick="this.form.submit();"> Aventura<br>
        <input type="checkbox" name="genero" value="esportes" onclick="this.form.submit();"> Esportes<br>
        <input type="checkbox" name="genero" value="rpg" onclick="this.form.submit();"> RPG<br>
        <input type="checkbox" name="genero" value="arcade" onclick="this.form.submit();"> Arcade<br>
    </form>
</div>

OBS: Check boxes offer the option to mark more than one item. If this is the intention HTML should be structured as follows. DEMO

  • Add to the input name the [], when submitting the form it will be sent as an array..

    <div class="prog">
    <legend class="">Genero</legend>
    <form action=""  method="post">
        <input type="checkbox" name="genero[]" value="acao"> Ação<br>
        <input type="checkbox" name="genero[]" value="aventura"> Aventura<br>
        <input type="checkbox" name="genero[]" value="esportes"> Esportes<br>
        <input type="checkbox" name="genero[]" value="rpg"> RPG<br>
        <input type="checkbox" name="genero[]" value="arcade"> Arcade<br>
        <input type="submit" value="Enviar">
    </form>
    

Example in PHP on the page where the action will occur

if(!empty($_POST['genero'])) {
    foreach($_POST['genero'] as $item) {
            //açãos
    }
}

Browser other questions tagged

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