Alert in Swicth Case in php

0

I want to be able to show an alert that says please select an option when no radio option has been selected. the code that I have test is as follows.

calculo.php

class Calculadora{
    public function calcular($n1, $n2, $operador)
    {   
        $ope = $_POST['operador'];
        switch ($ope) {
            case 0:
                return $n1 + $n2;
                break;
            case 1:
                return $n1 - $n2;
                break;
            case 2:
                return $n1 * $n2;
                break;
            case 3:
                return $n1 / $n2;
                break;
            default:
                echo "<script>alert('Seleccione una opción');</script>";
                break;
        }
    return $res;
    }
}
    <?php require_once "calculo.php"; 
          $calculadora = new Calculadora();

          $num1 = $_POST['numero_1'];
          $num2 = $_POST['numero_2'];
          $operador = $_POST['operador'];
          $operacion = array('suma', 'resta', 'multiplicacion', 'division');

?>

HTML

<form method="POST" action="" name="form1">
    <input type="number" name="numero_1" required>
    <input type="number" name="numero_2" required>
    <input type="radio" name="operador" value="0">
    <input type="radio" name="operador" value="1">
    <input type="radio" name="operador" value="2">
    <input type="radio" name="operador" value="3">
    <input id="boton" type="submit" value="Resultado">
    <?php echo "El resultado de la ".$operacion[$operador]." es:".$calculadora->calcular($num1, $num2, $operador);?>
</form>
    
asked by Anderviver 08.03.2018 в 18:29
source

1 answer

0

Replaces this line

$ope = $_POST['operador'];

By:

$ope = isset($_POST['operador']) ? $_POST['operador'] : -1;

With this you will avoid an error when the form does not send the value of the operator when leaving the radios unselected. And assigning a value to $ ope when this happens will fall on your default switch

    
answered by 08.03.2018 / 19:02
source