I have a drop down select inside of a form on my page nice.php which is submitted using a button
<form action="nice.php" method="post">
<select name="CarList">
<option value="0"> - Select Car - </option>
<option value="AM">Aston Martin</option>
<option value="KG">Koenigsegg</option>
<option value="MB">Mercedes Benz</option>
</select>
<input type="submit">
</form>
After making a selection is it possible to submit the form, reload the same page however with the value from the dropdown into a php variable $SelectedCar?
if(!empty($_POST['CarList'])){
$SelectedCar = $_POST['CarList'];
echo $SelectedCar;
}else{
echo '<p>No Selection has been made and submitted yet</p>';
}
Add the code to the top of your php page and remove the form tags. This should do a post back to the same page. (Remember to check if any variables are set in $_POST )
I haven't tested this suggestion yet but it should work
** Edit.
So Your HTML should look something like this:
<?php
if(isset($_POST['CarList']) && !empty(isset($_POST['CarList'])){
$CarListValue = $_POST['CarList'];
if($CarListValue != 0){ // a selection has been made using car list
$SelectedCar = $CarListValue
echo $SelectedCar // should print either 'AM', 'KG', or 'MB'
}
else{
echo '<p>No Selection has been made and submitted yet</p>';
}
}
?>
<html>
<head>
<title>Nice.php</title>
</head>
<body>
<select name="CarList">
<option value="0"> - Select Car - </option>
<option value="AM">Aston Martin</option>
<option value="KG">Koenigsegg</option>
<option value="MB">Mercedes Benz</option>
</select>
<submit>Submit Form</submit>
</body>
</html>
You could then take your validation to another level and change the php code like this as well:
<?php
$ValidCars = array('AM','KG','MB');
if(isset($_POST['CarList']) && !empty(isset($_POST['CarList'])){
$CarListValue = $_POST['CarList'];
if(in_array($CarListValue,strtoupper($ValidCars),false) !== true){
die('<b>The car selection you made is invalid</b>');
}
if($CarListValue != 0){ // a selection has been made using car list
$SelectedCar = $CarListValue
echo $SelectedCar // should print either 'AM', 'KG', or 'MB'
}
else{
echo '<p>No Selection has been made and submitted yet</p>';
}
}
?>
I just want to say again that this code is untested but the in theory the code should work without any error
Related
I’ve been building a series of webpages that allows for dynamic data manipulation (CRUD). The pages are built with HTML, CSS, and PHP.
At this stage of the project, my goal is to have the site return an error message if data is not entered into a particular field.
I've made a small sandbox for the problem.
At the top of the page, I included the following PHP logic to outline the variables and how the page will behave if data is entered into the form fields (or not entered):
$routeType = "";
$hasRouteType = false;
$routeTypeError = false;
if( isset($_POST["add"]) ) {
if( isset($_POST['route-type']) ) {
$routeType = $_POST['route-type'];
if($routeType) {
$hasRouteType = true;
} else {
$routeTypeError = "Please select a route type.";
}
}
}
I made a dropdown menu as one of the elements in the form as follows:
<form method='POST'>
<field>
<label>Route Type</label>
<select name="route-type" id="route-type">
<option value="" selected="true" disabled="disabled">What type of route is this?</option>
<option value="interstate">Interstate</option>
<option value="stateRoute">State Route</option>
<?php if($routeTypeError) { ?>
<p class='error'><?=$routeTypeError?></p>
<?php } ?>
</select>
</field>
<form>
<button class='route-button' type="submit" name='add'>Add route</button>
At this stage, when the user doesn't choose anything from the dropdown, no error message is returned -- again, this is the goal of this stage of the project.
Steps I've tried to solve the problem so far (these didn't work)
I’ve tried changing the logic in the principal foreach statement.
if($routeType) {
$hasRouteType = true;
if($routeType != "") {
$hasRouteType = true;
I’ve tried changing the data type of the $routeType variable when it's initialized.
I’ve tried adding selected=“true” and disabled=“disabled” to the top element in the dropdown menu to make it the first thing that appears on the page — and also to make it impossible for the user to select it as an option from the menu.
<option value="" selected="true" disabled="disabled">What type of route is this?</option>
I've been told that "looping through the option elements" might be a possible solution, but I don't know how to implement this.
My goal is to have the error message "Please select a route type." returned if the user does not select anything from the dropdown menu.
Thanks very much for the help!
You need an option field with empty value and the required.
Solution with client-side check
<select name="route-type" id="route-type" required="required">
<option value="">What type of route is this?</option>
<option value="A" >Select A</option>
<option value="B" >Select B</option>
</select>
You don't need php for this.
Try to submit this without select a value and you will get an error message.
All html and javascript checks are just goodies, you always have to check all values with php(when you use php) when you get them from a form.
Never trust any data and check every data you receive!
UPDATE:
Maybe this is a possible solution you looking for with php:
Solution with php check
<?php
$route_check = array(
'interstate'
,'stateRoute'
);
if(!in_array($_POST['route_type'] ?? '' , $route_check)){
?>
<form method="post">
<select name="route_type">
<option value="">SELECT A TYPE</option>
<option value="interstate">interstate</option>
<option value="stateRoute">stateRoute</option>
</select>
<input type="submit">
</form>
<?php
}
else{
echo "DO SOMETHING";
}
?>
If you wan't to check with the required option also on the client-side use:
<select name="route_type" required="required">
You can also build your option fields with a loop and use the values from the array.
Solution with php check and custom error message(javascript alert):
<?php
$route_check = array(
'interstate'
,'stateRoute'
);
if(!in_array($_POST['route_type'] ?? '' , $route_check)){
if( ($_POST['SEND'] ?? '') === 'SEND'){
echo "<script>alert('Please select type')</script>";
}
?>
<form method="post">
<select name="route_type">
<option value="">SELECT A TYPE</option>
<option value="interstate">interstate</option>
<option value="stateRoute">stateRoute</option>
</select>
<input type="submit" name="SEND" value="SEND">
</form>
<?php
}
else{
echo "DO SOMETHING";
}
?>
Solution with php check and custom error message(php in option field):
<?php
$route_check = array(
'interstate'
,'stateRoute'
);
if(!in_array($_POST['route_type'] ?? '' , $route_check)){
if( ($_POST['SEND'] ?? '') === 'SEND'){
$MESSAGE = 'NO TYPE SELECTED';
}
else{
$MESSAGE = 'SELECT A TYPE';
}
?>
<form method="post">
<select name="route_type">
<option value=""><?php echo $MESSAGE; ?></option>
<option value="interstate">interstate</option>
<option value="stateRoute">stateRoute</option>
</select>
<input type="submit" name="SEND" value="SEND">
</form>
<?php
}
else{
echo "DO SOMETHING";
}
?>
This is just a small example of how it could work, of course you can further optimize and adapt the code
EDIT!!! : LINK = http://i299291.iris.fhict.nl/PHP31/DV3/DV3.php
My problem:
I've made two dropdown boxes with several options. The php code is working and the query gets the right result from the database. But now i want to compare two options.
This is what i've got so far, the problem now is the entire page refreshes when i enter the second value from the other dropdown box.
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<form id = "leftDropdown" action= "" method="post">
<select name="objectLinks">
<option value="school">School</option>
<option value="klas">Klas</option>
<option value="geslacht">Geslacht</option>
<option value="lengte">Lengte (CM)</option>
<option value="kg">Gewicht (KG)</option>
<option value="opleiding">Opleiding Ouders</option>
<option value="leeftijdJaar">Leeftijd</option>
<option value="interventie">Deelname interventie?</option>
<option value="pestenVoor">Pestincidenten voor interventie</option>
<option value="pestenNa">Pestincidenten na interventie</option>
<option value="bmi">BMI waarde</option>
<option value="overgewicht">Overgewicht</option>
<option value="allochtonenPerc">Percentage Allochtonen</option>
</select>
<input type="submit" name="sendLinks" value="Go!">
</form>
<form id = "rightDropdown" action= "" method="post">
<select name="objectRechts">
<option value="school">School</option>
<option value="klas">Klas</option>
<option value="geslacht">Geslacht</option>
<option value="lengte">Lengte (CM)</option>
<option value="kg">Gewicht (KG)</option>
<option value="opleiding">Opleiding Ouders</option>
<option value="leeftijdJaar">Leeftijd</option>
<option value="interventie">Deelname interventie?</option>
<option value="pestenVoor">Pestincidenten voor interventie</option>
<option value="pestenNa">Pestincidenten na interventie</option>
<option value="bmi">BMI waarde</option>
<option value="overgewicht">Overgewicht</option>
<option value="allochtonenPerc">Percentage Allochtonen</option>
</select>
<input type="submit" name="sendRechts" value="Vergelijk!">
</form>
<div id = "leftDiv">
<?php
include_once 'dv3ToDB.php'; // connect to database *local or at school's server*
session_start();
if(isset($_POST['sendLinks'])){
$selectedValLinks = $_POST['objectLinks'];
// echo "Jij selecteerde: ".$selectedVal;
echo "<script>console.log('$selectedValLinks');</script>";
// $_SESSION["valLinks"] = $selectedValLinks;
// echo $_SESSION["valLinks"];
$query = "SELECT ($selectedValLinks) FROM pesten ORDER BY ($selectedValLinks) * 1";
$result = $conn->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "Gevonden data in ".$selectedValLinks.": " . $row["$selectedValLinks"] . "<br>" ;
}
}else{
echo "0 results";
}
}
?>
</div>
<div id = "rightDiv">
<?php
if(isset($_POST['sendRechts'])){
$selectedValRechts = $_POST['objectRechts'];
// echo "Jij selecteerde: ".$selectedVal;
echo "<script>console.log('$selectedValRechts');</script>";
// $_SESSION["valRechts"] = $selectedValRechts;
// echo $_SESSION["valRechts"];
$conn = mysqli_connect($host,$username,$password,$database)
or die("verbinding mislukt:".mysqli_connect_error());
$query = "SELECT ($selectedValRechts) FROM pesten ORDER BY ($selectedValRechts) * 1";
$result = $conn->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "Gevonden data in ".$selectedValRechts.": " . $row["$selectedValRechts"] . "<br>" ;
}
}else{
echo "0 results";
}
}
?>
</div>
</body>
</html>
i'm running it local now, let me know if you need me to build a database online to help me out.
How can i code it so the PHP output stays in de left DIV and/or the right DIV?
Thank you so much guys and girls! :)
If you need to use only PHP, without any JavaScript (which could allow you to display the result from the database after selecting each option without reloading the page), I'd suggest that, after submitting one form, you add it's result as a hidden input for the other form, so you could read this variable after submitting the 2nd form.
Like this:
<? // Your code for getting the result of the 1st form above returns a variable $res1
// Now insert this into the 2nd form:?>
<input type="hidden" name="stored2" value="<?echo $res1;?>"/>
This way, you can read the variable $_POST["stored2"] after submitting the 2nd form to get what the 1st form returned before.
Do the same for the 1st form to store the results of the 2nd form if it was filled first.
This way, you can compare the results of submitting 2 forms while using only PHP.
EDIT:
You'll need to place all the database requests before the forms to use this method, and just echo the result in the div later.
You want to make a new <iFrame> and then set that <iFrame>'s id as the target for your form.
e.g.:
<form ... target="newframe">
...
</form>
<iFrame id="newframe"></iFrame>
As Lal mentioned you don't need two forms, just one will work.
You need some code that updates the option to selected, if you don't want it to "stick" on page refresh.
Further reading here;
http://www.w3schools.com/tags/att_option_selected.asp
and here
html select option SELECTED
Even try Jquery;
http://forum.jquery.com/topic/how-to-dynamically-select-option-in-dropdown-menu
If I have a select form, for example:
<form action='?' method='get' name='form_filter' class="sortoptions" >
<select name="sort" >
<option value="None">None</option>
<option value="PriceLow">Price (Low to High)</option>
<option value="PriceHigh">Price (High to Low)</option>
<option value="NameAZ">Name (A-Z)</option>
<option value="NameZA">Name (Z-A)</option>
</select>
I'm submitting using the GET method but need a way of when its been submitted and on the results page the option which was selected to be displayed.
So say if 'Price (High to Low)' is selected it will then be displayed in the select box on the results page after its been submitted
Any ideas?
Thanks!
When you will submit the form (assuming there is a submit button in your form), all data will be sent to PHP and you will retrieve all your data inside $_GET (the global var)
$_GET['sort']
will contain the value selected.
Then if you want to pre select, you just have to add some PHP code inside your HTML
<option value="PriceLow" <?php echo ((!empty($_GET['sort']) && $_GET['sort'] == 'PriceLow') ? 'selected="selected"' : '') ?>>Price (Low to High)</option>
You have to do the same for each option of the select.
That will allow you to preselect the good option after a first submit.
Solution 2:
If you don't wan to insert too much PHP inside your HTML code, you can store the posted value inside a javascript var and then, select the good option when the DOM is loaded (using a good JS library like jQuery for example)
Your HTML code:
<select name="sort" >
<option value="None">None</option>
<option value="PriceLow">Price (Low to High)</option>
<option value="PriceHigh">Price (High to Low)</option>
<option value="NameAZ">Name (A-Z)</option>
<option value="NameZA">Name (Z-A)</option>
</select>
And some JS code in <script> tag
// Need jQuery !
$(document).ready(function() {
// Generate the selected var in JS using the value in PHP
var selectedOption = '<?php echo $_GET['sort']; ?>';
// Select the selected option and append the selected attribute
$("select[name=sort] option[value=" + selectedOption + "]").attr('selected', 'selected');
});
This code will automatically select the good option once the page is loaded.
Info: The good point is that you have a more clear and maintanable HTML code. The bad point is that if JavaScript is not enabled on the client, your automatic selection will not work (it will always work when you are using PHP to add "selected" in HTML). So you have to evaluate pro and cons and make your choice.
Note: you can leave the action empty instead of "?"
$_GET['sort']
in the submitted page will give you the selected option. And to check whether the form has been submitted:
if(isset($_GET['submit'])) {
// do something with the result
}
where 'submit' is the name of your submit button.
Try this code, it's probably what you would want. I assume you're writing it in your .php files or your other extensions, perhaps .html have php code enabled in them (maybe via .htaccess file)
<?php if (isset($_GET['sort'])){ ?>
<?php $sel= $_GET['sort']; # format? ?>
<strong><?php print($sel);?></strong>
<?php } ?>
<form action='' method='GET' name='form_filter' class="sortoptions" >
<select name="sort" >
<?php
$ff = Array(
'None' => 'None',
'PriceLow' => 'Price (Low to High)',
'PriceHigh' => 'Price (High to Low)',
'NameAZ' => 'Name (A-Z)',
'NameZA' => 'Name (Z-A)',
);
?>
<?php foreach ($ff as $v => $t) {?>
<option value="<?php print($v);?>" <?php if (isset($_GET['sort']) && ($_GET['sort'] == $v)) print('selected="selected"');?>"><?php print($t);?></option>
<?php } ?>
</select>
<input name="submit" type="submit" />
</form>
Having some trouble here with this.
The setup:
A select object with a choice of "Other"
User selects "Other".
Script runs when this specific value is chosen, and dynamically changes the class of input object from "hide" to "show" (hidden and visible with css display).
<p>Select a Grade:</p>
<select name="grade" id="grade" onchange="changeCssClass('otherGrade')">
<option value="No Specified Grade">Please Select</option>
<option value="201">201</option>
...
<option value="Secondary">Secondary</option>
<option value="otherGrade">Other</option>
</select>
<p>If "Other":</p>
<?php
$otherGrade = $_POST['grade'];
if($otherGrade = "otherGrade")
{
echo("<script language='javascript' type='text/javascript'>
function changeCssClass(objInputID)
{
if(document.getElementById(objInputID).className=='hide')
{
document.getElementById(objInputID).className = 'show';
}
else
{
document.getElementById(objInputID).className = 'hide';
}
}
</script>");
}
else
{
echo ("");
}
?>
<input type="text" name="otherGrade" id="otherGrade" class="hide" />
Should I remove the onchange event from the select object? If so, I am at a loss as how to have the script executed.
Any solutions would be greatly appreciated.
The script should always be included in your page, since you want this to run while you make the changes in the dropdown list..
<script language='javascript' type='text/javascript'>
function changeCssClass(objInputID, currentVal, correctVal)
{
if(correctVal == currentVal)
{
document.getElementById(objInputID).className = 'show';
}
else
{
document.getElementById(objInputID).className = 'hide';
}
}
</script>
<p>Select a Grade:</p>
<select name="grade" id="grade" onchange="changeCssClass('otherGrade', this.value, 'otherGrade')">
<option value="No Specified Grade">Please Select</option>
<option value="201">201</option>
...
<option value="Secondary">Secondary</option>
<option value="otherGrade">Other</option>
</select>
<p>If "Other":</p>
<input type="text" name="otherGrade" id="otherGrade" class="hide" />
Live example at : http://www.jsfiddle.net/MVymF/
why are you putting this in the post event? you can just render this as standard javascript as part of the page.
On post , the page will be refreshing , ad on reloading you are not saving the selected value of the select box.
The select box is not keep selected after posting. You have to do that.
>Other
As the value of option change the display hide also gone.
Fix that
If no need to submit the page . use this
http://api.jquery.com/val/
check demo of select
Im trying to implement the search feature in my website.
when the search keyword is entered in the textbox, and the category combo is selected, the form will be Posted and the result will be shown on the same page.
what i want is to keep the selected category of the combo by default in the form after posted
For eg., If i select the category 'Automobiles' in the combo and click search, after form submit, the combo should show the automobiles as default selected option. Please help me. Any help will be appreciated
I assume you get categories from database.
you should try:
<?php
$categories = $rows; //array from database
foreach($rows as $row){
if($row['name'] == $_POST['category']){
$isSelected = ' selected="selected"'; // if the option submited in form is as same as this row we add the selected tag
} else {
$isSelected = ''; // else we remove any tag
}
echo "<option value='".$row['id']."'".$isSelected.">".$row['name']."</option>";
}
?>
Assuming that by "combo" you mean "A regular select element rendering as a drop down menu or list box" and not "A combobox that is a combination of a drop down menu and free text input":
When outputting the <option> elements, check the value against the submitted data in $_POST / $_GET and output selected (in HTML) or selected="selected" (in XHTML) as an attribute of the option element.
Here is the JQuery way I am using.
<select name="name" id="name">
<option value="a">a</option>
<option value="b">b</option>
</select>
<script type="text/javascript">
$("#name").val("<?php echo $_POST['name'];?>");
</script>
But this is only if you have jquery included in your webpage.
Regards
<?php
$example = $_POST["friend"];
?>
<form method="POST">
<select name="friend">
<option value="tom" <?php if (isset($example) && $example=="tom") echo ' selected';?>>Thomas Finnegan</option>
<option value="anna" <?php if (isset($example) && $example=="anna") echo ' selected';?>>Anna Karenina</option>
</select>
<br><br>
<input type="submit">
</form>
This solved my problem.
This Solved my Problem. Thanks for all those answered
<select name="name" id="name">
<option value="a">a</option>
<option value="b">b</option>
</select>
<script type="text/javascript">
document.getElementById('name').value = "<?php echo $_GET['name'];?>";
</script>
$countries_uid = $_POST['countries_uid'];
while($row = mysql_fetch_array($result)){
$uid = $row['uid'];
$country = $row['country_name'];
$isSelected = null;
if(!empty($countries_uid)){
foreach($countries_uid as $country_uid){//cycle through country_uid
if($row['uid'] == $country_uid){
$isSelected = 'selected="selected"'; // if the option submited in form is as same as this row we add the selected
}
}
}else {
$isSelected = ''; // else we remove any tag
}
echo "<option value='".$uid."'".$isSelected.">".$country."</option>";
}
this is my solutions of multiple select dropdown box after modifying Mihai Iorga codes
After trying al this "solves" nothing work. Did some research on w3school before and remember there was explanation of keeping values about radio. But it also works for Select option. See here an example. Just try it out and play with it.
<?php
$example = $_POST["example"];
?>
<form method="post">
<select name="example">
<option <?php if (isset($example) && $example=="a") echo "selected";?>>a</option>
<option <?php if (isset($example) && $example=="b") echo "selected";?>>b</option>
<option <?php if (isset($example) && $example=="c") echo "selected";?>>c</option>
</select>
<input type="submit" name="submit" value="submit" />
</form>
Easy solution:
If select box values fetched from DB then to keep selected value after form submit OR form POST
<select name="country" id="country">
<?php $countries = $wpdb->get_results( 'SELECT * FROM countries' ); ?>
<option value="">
<?php if(isset($_POST['country'])){echo htmlentities($_POST['country']); } else { echo "Select Country *"; }?>
</option>
<?php foreach($countries as $country){ ?>
<option <?php echo ($_POST['country'] == $country->country_name ? 'selected="selected"':''); ?> value="<?php echo $country->country_name; ?>"><?php echo $country->country_name; ?>
</option>
<?php } ?>
</select>