Not printing my selected checkbox

Asked

Viewed 41 times

1

Good evening, I created 3 checkbox and made an array method for when I click send it shows me the checkbox selected with your value, but this is not happening, I made this scheme because I am testing so that I put in my original form that I will need to list my checkbox selected...

Can someone help me?

html:

<html>
<head>
<title>Teste de checkbox</title>
</head>
<body>
    <h1>Teste de check</h1>

    <form method="post" action="form.php">

    <input type="checkbox" name="cor" value="azul">

    <input type="checkbox" name="cor" value="vermelho">

    <input type="checkbox" name="cor" value="amarelo">


    <input type="submit" name="olhar">

    </form>


</body>
</html>

php form.:

<?php 
if(isset($_POST["cor"])) {

    for($i = 0; $i < count($_POST["cor"]); $i++) {

        echo "a cor ".$_POST["cor"] [$i]." foi selecionada";

    }
}

?>

Thank you...

1 answer

3


You have only "vectorized" your inputs, as you used the same name, and then want to recover the value of all, needs to be this way:

<form method="post" action="form.php">

<input type="checkbox" name="cor[]" value="azul">

<input type="checkbox" name="cor[]" value="vermelho">

<input type="checkbox" name="cor[]" value="amarelo">


<input type="submit" name="olhar">

</form>

I hope I’ve helped!!!

  • 1

    Thank you... helped a lot

  • The curious thing is that you can even receive POST of repeated names in PHP without it, but it takes a lot of work.

  • Really? I think I’ve seen someone talk about, but in these cases I always use it that way, when necessary...

  • 1

    @Localhost in PHP [] is the most suitable path even, but always putting "value" in these cases. The fact is that when you repeat the name, it is not a POST limit, but PHP itself overwrites the previous value. POST goes with all the data. color=a&cor=b*color=c, so pro PHP is only worth the last one. As in PHP the [] means "the next free input", there is an array.

  • 1

    A good site to test this is https://httpbin.org/ - try making a form for httpbin.org/post without using the [], you will see that he can still get all the values marked. Follow a link demonstrating: http://codepen.io/bacco/pen/pNBGag

  • Interesting @Bacco, was not aware of the POST write mode, but the one of the array knew on its own PHP

  • I commented more of curiosity, in PHP you don’t even have to think, that’s what you really answered.

Show 2 more comments

Browser other questions tagged

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