Reputation: 45
Referring to this example PHP form that loads content based on dropdown option
Solution 1, PHP
1) index form
<form action="loadPage.php" method="POST" name="theForm" id="theForm">
<select form="theForm" name="selectedPage">
<option value="page_1">Page 1</option>
<option value="page_2">Page 2</option>
...
</select>
<input type="submit" value="Load page" />
</form>
2) A PHP handler
<?php
//loadPage.php
$requested_page = $_POST['selectedPage'];
switch($requested_page) {
case "page_1":
header("Location: page_1.php");
break;
case "page_2":
header("Location: page_2.php");
break;
default :
echo "No page was selected";
break;
}
?>
I just want to do It without the need of clicking on submit. I want to achieve this just by clicking on the dropdown list value then checks if it's equal to the value in the Php file if yes show the page.
Thanks a lot.
Upvotes: 2
Views: 4166
Reputation: 41737
This will cause a "redirect" when you select an option in the dropdown:
Add an onchange
event to the select
to change the current browser location.
Change the select option values to the URLs for the pages.
(You might then drop the PHP header directions in loadPage.php
. Not needed anymore.)
<select form="theForm" name="selectedPage"
onchange="if (this.value) window.location.href=this.value">
<option value="page_1.php">Page 1</option>
<option value="page_2.php">Page 2</option>
</select>
Answers for the questions asked by Jay Blanchard in the comment section:
Can this be done without inline JavaScript (for ease of maintenance and reuse-ability)?
Sure, thats possible, too. For instance, with jQuery:
$('#SelectId').change(function() {
//alert( this.value ); // or $(this).val()
window.location.href = 'http://' + this.value;
});
See http://api.jquery.com/change
Or you may bind with .on('change')
$('#SelectId').on('change', function() {
//alert( this.value ); // or $(this).val()
window.location.href = 'http://' + this.value;
});
Can you do it without jQuery?
Sure, thats possible, too. You might select the element by using document.getElementById()
and bind the event handling with addEventListener
.
window.onload = function() {
var select = document.getElementById('SelectId');
var handler = function() {
if(select.value) {
window.location.href = 'http://' + select.value;
}
};
select.addEventListener('change', handler, false);
};
Upvotes: 3
Reputation:
Write html as follow:
<select form="theForm" name="selectedPage" onchange="this.form.submit()">
<option value="page_1">Page 1</option>
<option value="page_2">Page 2</option>
</select>
This will submit form when you select option.
Upvotes: 4