I’m looking for a solution/best practice for the following issue.
I have a page with an HTML form with one dropdown list and a submit button. Underneath of the dropdown box is an empty space that I would like to populate with form inputs based on the selected value in the dropdown box. Im thinking this can be done in JavaScript but I would much prefer a PHP/client side solution if possible.
Example HTML:
<form name="initialdropdown" action="#" method="post">
<select name="action">
<option value="default">--select--</option>
<option value="a">Option 1</option>
<option value="b">Option 2</option>
<option value="c">Option 3</option>
<option value="d">Option 4</option>
</select>
<input type="submit" name="submit" value="submit"></input>
</form>
I’ve explored calling this php script from the form action:
<?php
$getOption = $_POST['action'];
$addUrl = $getOption.".php";
include $addUrl;
header("Location: htmlpage.php");
?>
and then create several different php files (a.php,b.php,c.php, etc. In each of the files then including the HTML form that I would like to echo out wrapped in a function, and including the function in the main HTML page. I do not feel comfortable that this is a good way to do it. Can anyone shed some light on the best way to go about this?
If you want to display something on the HTML form that updates as you pick different options, JavaScript is the natural choice because you don’t have to go and make requests to the server which means moving around data and waiting for responses. JavaScript can simply change the page as many times as you want while the user interacts with the page.
However, if you are dead set on generating whatever you want to display on that form with PHP, you could have PHP output the display information to the page right into the JavaScript. Then the JavaScript displays this data from PHP. Or, you can use an AJAX call to PHP to request the data to display each time a different option is chosen.
update
Given your latest comment, you could very easily set up more form options without using PHP. In the HTML set up all the various form options you might want to show, but hide the optional parts with CSS. Then reveal each section as needed with a little JavaScript. jQuery can make this even easier.