samedi 29 mai 2021

"Switch" and "If" conditional is not checking my variable values on PHP

Neither "if" nor "switch" are working for me. Could you please help me?

switch ($subject2) {
       case '-':
              $input = $subject1;
              break;
       default:
              $input = $subject1.' and '.$subject2;
}


echo $input;

I need to check if "subject2" has a dash or not.

If it has a dash, then my variable "input" needs to store the value of "subject1".

If it doesn't have a dash, then my variable "input" needs to store the values of "subject1" and also "subject2".

If I try using a 0 instead (without quotes), it works. If I try the word "none" instead of a dash, it doesn't work.


Here's a sample of the code I'm running:

<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>

<h1>Form</h1>

<form action="" method="get">

<!--First field of the form-->

<label for="name">Choose an option(mandatory):</label>

<input list="opcionLista1" id="sujeto1" name="sujeto1" value="<?php echo isset($_GET["sujeto1"]) ? $_GET["sujeto1"] : ''; ?>" onfocus="this.value=''">

<datalist id="opcionLista1">
   <option value="-">
   <option value="Juan">
   <option value="Pedro">
   <option value="Oliver">
</datalist> <br><br>


<!--Second field of the form-->

<label for="name">Choose an option (Optional):</label>

       <input list="opcionLista2" id="sujeto2" name="sujeto2" value="<?php echo isset($_GET["sujeto2"]) ? $_GET["sujeto2"] : ''; ?>" onfocus="this.value=''">

<datalist id="opcionLista2">
   <option value="-">
   <option value="Mariana">
   <option value="Estefa">
   <option value="Lucía">
</datalist>

<!--"Send" button-->

<input type="submit" name="enviar" value="buscar">

</form><br><br><br>

<!--Saving the field values on JavaScript to send them to PHP afterwards-->

<script type="text/javascript">
var sujeto1 =  document.getElementById("sujeto1").value;
var sujeto2 = document.getElementById("sujeto2").value;

<?php 
       $sujeto1 = "<script>document.write(sujeto1)</script>";
       $sujeto2 = "<script>document.write(sujeto2)</script>";

?> 
</script><br><br><br>

<!--Finally, the "Switch" code meant to check the value of the second field, that would define the value of $input according to the option selected-->

<?php 

switch ($sujeto2) {
       case '-':
       $input = $sujeto1;
              break;
       default:
              $input = $sujeto1.' and '.$sujeto2;
}

<!--This echo should show the value stored on my variable.-->

echo $input;

?>

</body>
</html>

The website should make you choose two options. The first one should be (will be) mandatory, the second one should be optional.

When you click on "search", it should display the result. But if you choose a dash on the second field, it will say something like "juan and -" instead of just "Juan".

Aucun commentaire:

Enregistrer un commentaire