Reputation: 6474
I'm writing a simple PHP program with a form that has multiple fields to be filled in.
Among the fields is a <select>
box.
I want the same form to post to 3 different URLs, determined by which of the three values have been selected in that <select>
box.
How do I code something like this in PHP (with a typical HTML form)?
Any code samples/guides would be helpful.
I (being a newbie) am especially confused about this part: The form opening tag already specifies the target URL, so how can I change this later, depending on the input given by user in the drop down box, as the drop down box's HTML code is after the opening form tag(which already declares the form's target URL)?
Upvotes: 1
Views: 1415
Reputation: 13608
You can use JavaScript like this:
<form method="get" action="http://example.com/url1">
<select name="_" onchange="this.form.action=this.value">
<option value="http://example.com/url1">URL1</option>
<option value="http://example.com/url2">URL2</option>
</select>
<input type="submit" value="Submit" />
</form>
Whenever the value in <select>
changes, the form's action is updated to the required URL.
Upvotes: 1
Reputation: 640
With javascript you could grab the value of the drop down option selected and populate the form's action attribute.
With php, you could have one "results.php" page that could repackage the $_POST vars and send to the correct URL based on the $_POST['send_to_this_url'] var.
I'd do the JS version.
Upvotes: 1
Reputation: 239311
You can't do this in PHP. You must dynamically alter the form's action
attribute with JavaScript to point to the URL you wish the form to submit to.
This can only be done in JavaScript, as only JavaScript has access to the client's browser where the form is being interacted with.
The alternative would be to have your form always submit to the same URL, and handle the submitted data with branching logic in PHP. I would prefer this method, as there is no requirement for JavaScript on the client.
Upvotes: 1