Reputation: 87
I am having trouble trying to figure out how to navigate to different web pages using a drop down list and submit. I have three forms:
In my main.php page I have a drop down list consisting of only two options 'second' and 'third'. How can I use these two options to navigate to other php pages? For example, if I selected the option 'two' and click submit, the page should then take me to the second.php page. And if I select option 'three', I will be taken to the third.php page.
Also, once I am directed to one of the php pages, how can I then be able to go back to the 'main.php' page if I decide to go to the other php page instead? (I thought perhaps the use of a back button).
Below is part of my 'main.php' page:
<label>Select the page you wish to go:</label></td>
<select name="pages"/>
<option value="two.php">Second</option>
<option value="three.php">Third</option>
</select></td>
Upvotes: 1
Views: 3447
Reputation: 6002
Jquery solution
HTML CODE:
<form id="frm" method="post" action="" >
<label>Select the page you wish to go:</label>
<select name="pages"/>
<option value="two.php">Second</option>
<option value="three.php">Third</option>
</select>
<input type="submit" name="sub" value="Finish" />
</form>
JQUERY CODE
$('#frm').on('submit',function () {
var nextPage= $('select option:selected').val();
$(this).attr('action',nextPage);
return true;
});
Happy Coding :)
Upvotes: 0
Reputation: 619
You can do multiple things. If you dont wan't to rely on javascript, make the form submit to a file like router.php
.
inside router.php
put:
<?php
if (isset($_POST['pages']) {
header('Location: ' . $_POST['pages']);
}
Which will effectively forward the request to the page you submitted in the select.
You also have to change your html a bit:
<label>Select the page you wish to go:</label></td>
<form method="post" action="router.php">
<select name="pages"/>
<option value="two.php">Second</option>
<option value="three.php">Third</option>
</select>
<input type="submit" value="go there" />
</form>
If you are fine with javascript go with @notulysses's answer, its way easier and quicker.
Using POST
values directly in a header method is kinda nasty imo.
Upvotes: 0
Reputation: 44581
On <select></select>
value change :
HTML :
<select name="pages" onChange="my_function(this)">
JavaScript :
function my_function(element){
document.location.href = element.value
}
On <button></button>
click :
HTML :
<button onClick="my_function()"></button>
JavaScript :
function my_function(){
document.location.href = document.querySelector('select[name="pages"]').value
}
Upvotes: 3