0

Can you put a PHP IF() statement within an HTML form?

I am looking to make an adaptive form depending on the previous selected options.

Snippet:

<label for="#">Pick a #:</label><br/>
<select id="#" name="#" form="#" value="<?php echo $#;?>" required>
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3">3</option>
          <option value="4">4</option>
          <option value="5">5</option>
        </select><br/>
        <br/>
 <label for="Reason">Reason:</label><br/>
 <select id="Reason" name="Reason" form="Reason" value="<?php echo $Reason;?>" required>
        <?php

        if ($# === "1"){
        ?>
            <option value="R1">Unique</option>
            <option value="R2">Lonely</option>
            <option value="R3">Supreme Leader</option>
            <option value="R4">Excess Space</option>
        <?php
        }

The selection box does appear, but with no drop-downs, regardless what is selected in the "#" section.

Not opposed to using Javascript, just wondering if this is possible.

j08691
  • 204,283
  • 31
  • 260
  • 272
ECP03
  • 67
  • 8
  • 3
    No. This isn't possible as you describe. As you may be expecting, this has to be done with JS. – Jonnix Oct 12 '16 at 20:44
  • 1
    That's not how PHP works, the page needs to be submitted first. – BenM Oct 12 '16 at 20:45
  • I don't understand exactly what it is that you're trying to do – j08691 Oct 12 '16 at 20:45
  • 1
    `$#` is not even a valid variable name – u_mulder Oct 12 '16 at 20:45
  • 1
    Technically you could have php return the next set of options, but it would need to be done via an ajax call which would still involve javascript, so you'd be as well just doing the whole thing with javascript unless you have specific reasons for contacting the server between each question – Darren H Oct 12 '16 at 20:46
  • @u_mulder I suspect the OP just used `#` as representative of a name to avoid using the real ID, he could equally have used `my_var`, notice how the `#` is used in many places wherever a name or ID should be – Darren H Oct 12 '16 at 20:48
  • Thank you for the clarification and comments. Off to Javascript I go. – ECP03 Oct 12 '16 at 20:49

1 Answers1

3

This interaction, as you've mentioned, has to be dealt with in the client side and (probably) with JavaScript. PHP only processes the page on the server side once and then the page is submitted to the client. Once it's there, PHP is long gone and has no effect on the page.

Nir
  • 1,225
  • 12
  • 8