Validate if I select a value in the checkboxs

0

When I select one or more of the possible checkbox , it shows me the message or messages that I have in PHP , but if I do not select any of the possible checkbox I get the following error: "Notice: Undefined index: TypeM in C: \ xampp \ htdocs \ Task_02 \ action.php on line 11"

Line 11

$TipoM=$_POST["TipoM"];

How can I solve this error?

I enclose fragments of my codes:

HTML form

Elige tipo de mensaje: <br><br>   
        <select multiple name="TipoM[]">    
        <option value="Top_Secret" checked>Alto secreto</option>    
        <option value="Reserved">Secreto</option>    
        <option value="Indifferent">Indiferente su difusión</option>    
        <option value="Obligatory">Difusion obligatoria</option> 
        </select><br><br>

PHP CODE

   function Mostrar_TipoMensaje ($TipoM)
    {

            for ($i=0;$i<count($TipoM);$i++)    
            {     

                       if(($TipoM[$i])==("Top_Secret"))
                       echo 'TOP SECRET<br>';
                       else
                           echo("");

                       if(($TipoM[$i])==("Reserved"))
                       echo 'RESERVED<br>';
                      else
                           echo("");

                       if(($TipoM[$i])==("Indifferent"))
                       echo 'INDIFFERENT<br>';
                       else
                           echo("");

                       if(($TipoM[$i])==("Obligatory"))
                       echo 'OBLIGATORY<br>';
                       else
                           echo("");
             }


}
    
asked by Alex Vic 24.01.2018 в 14:42
source

2 answers

3

You can do the following:

If you come by post that key saves it in $ TipoM, but saves null

$TipoM=isset($_POST["TipoM"])?$_POST["TipoM"]:null;

On the other hand, in your function, you verify that if the variable by parameters is not null, you go through it.

function Mostrar_TipoMensaje ($TipoM)
{
    if($TipoM){

        for ($i=0;$i<count($TipoM);$i++)    
        {     

            if($TipoM[$i]=="Top_Secret")
                echo 'TOP SECRET<br>';
            else
               echo("");

            if($TipoM[$i]=="Reserved")
                echo 'RESERVED<br>';
            else
               echo("");

            if($TipoM[$i]=="Indifferent")
                echo 'INDIFFERENT<br>';
            else
               echo("");

            if($TipoM[$i]=="Obligatory")
                echo 'OBLIGATORY<br>';
            else
                echo("");
        }
    }
}
    
answered by 24.01.2018 / 15:03
source
0

The error thrown is when you do not select a value, the checkboxs do not send the value to the form. You must have some kind of validation like: !$_POST["TipoM"] , ask if you do not send anything.

Example

if(!$_POST["TipoM"]) {
    echo "debes seleccionar algo";
}else{
    //tu codigo
}
    
answered by 24.01.2018 в 14:59