select dropdown value based on session variable - php

i have a php form which submits data to another php for validation. if any fields are left blank the validator php sends a message back to original php form along with all the pre filled variables using session variables so that user doesn't have to fill them again.
i can use these session variables to fill in text boxes again like this
value="<?php echo $_SESSION['fname'] ?>"
but how to go about populating drop downs, radio buttons and check boxes?
thanks

For a select, checkbox or radio box you would need to check whether the values match. Something like:
<select name="fname">
<option value="1" <?php if($_SESSION['fname'] == 1) echo 'selected'; ?>>1</option>
<option value="2" <?php if($_SESSION['fname'] == 2) echo 'selected'; ?>>2</option>
</select>
It's easier if you are iterating through the values for the option field:
<select name="fname">
<?php foreach($array AS $key => $value) { ?>
<option value="<?php echo $value; ?>" <?php if($_SESSION['fname'] == $value) echo 'selected'; ?>><?php echo $value; ?></option>
<?php } ?>
</select>

A <select> element's selected <option> is not determined by it's value= attribute. In order to mark an option selected, the <option> element must have the selected attribute set on it, as follows:
<select>
<option>1</option>
<option selected>2</option>
<option>3</option>
</select>
In order to do this programmatically, you need to iterate through the options, and manually test for the correct option, and add selected to that.

... Noticed that your double quote at the end of the statement was misplaced, it should be:
<script>
$("#fname").val("<?php echo $_SESSION['fname'] ?>");
</script>

There is a far simpler method using JQuery. You can set Selects with .val() so make the most of it.
<script type="text/javascript">
$("#fname").val("<?php echo $_SESSION['fname']; ?>");
</script>
Don't forget to set the id of the select as well as the name to fname.

Related

PHP variable in header function in one drop list with two values [duplicate]

I'd like to post two values in one drop down option and I'm not sure about the best way to approach it.
The drop down list pulls data in from an external service. This data is 'id' and 'name'.
When I select an option in the drop down and then press submit I want the 'id' and the 'name' to be posted.
My code looks like this:
<select name="data">
<option>Select a name</option>
<?php foreach($names as $name): ?>
<option value="<?php echo $name['id']);?>">
<?php echo $name['name']);?>
</option>
<?php endforeach; ?>
</select>
I've tried putting in a hidden input field, but that then doesn't render out the drop down (instead it just creates a list).
I am using both the id and name elsewhere, so I don't want to have to post just the id and then have to get the name again, hence I want to post both of them at the same time.
Any recommendations?
You cannot post two values unless both of them appear in the value attribute. You can place both in, separated by a comma or hyphen and explode() them apart in PHP:
// Place both values into the value attribute, separated by "-"
<option value="<?php echo $name['id'] . "-" . $name['name']);?>">
<?php echo $name['name']);?>
</option>
Receiving them in PHP
// split the contents of $_POST['data'] on a hyphen, returning at most two items
list($data_id, $data_name) = explode("-", $_POST['data'], 2);
echo "id: $data_id, name: $data_name";
You may add a hidden field with the name "id" and then bind an onchange event listener to the <select>. inside the onchange function, get the value of the <select> and assign it to the "id" field.
<form>
<select name="name" onchange="document.getElementById('id').value=this.value">
<!--
...
options
...
-->
</select>
<input type="hidden" name="id" id="id" />
<input type="submit" />
</form>
You could output something like:
<option value="<?php echo $name['id']."_".$name['name'];?>">
Then use preg_splitor explode to separate the two once the form data is processed.
The only way to do this is to include both pieces of information in the value for the single option. Just use code like the following, and then when you get the value back, split the string at the first underscore to separate out the values.
<select name="data">
<option>Select a name</option>
<?php foreach($names as $name): ?>
<option value="<?php echo $name['id'] . "_" . $name['name']);?>">
<?php echo $name['name']);?>
</option>
<?php endforeach; ?>
</select>
Also, you could just leave the ID alone in your form, and then look up the id again when the user submits the form.
You could make as many hidden inputs as there are options, each with the name of one option value. The input's values are the contents of the options. In the second script, you can look for the dropdown value, and then take the value of the hidden input with that name.
We can pass it with data attribute, and can access in js,
<option value="<?php echo $name['id']);?>" data-name="<?php echo $name['name']);?>">One</OPTION>
var name = $(this).find(':selected').data('name');

Set variable in relation to a value

I am creating a listbox box with 2 optional values Ja(Yes) or Nein(No). Additional iam using a default Value which is taken from the database for the record.
Here the code:
<td>
<select name="s_BKAG">
<option selected="selected" ><?php $bkagbruggwert = ''.$abc['BKAG (Brugg)']. ''; if ($bkagbruggwert==1){echo 'Ja';} else {echo 'Nein';};?></option>
<option value="1">Ja</option>
<option value="0">Nein</option>
</select>
</td>
Problem: Now i want that when Yes or No is selected, then id should take their value and if nothing is selected it should take the Value of the preselected default value. But the problem is the variable which i have created has the value "Ja", it does not matter what I'am changing on the formular. I do not know if I overseeing something.
The code of variable defining is here:
$BKAG_Brugg = $_POST['s_BKAG'];
I could take $BKAG_Brugg and define a new variable which i am asking, if the $BKAG_Brugg is "Ja" then set 1 to the new variable. But it's my first project on php and i do not really now how to do the query for the new variable.
Can someone help me with that? i would be thankful for every little help.
regards:
okanog
I think you can do like this:
<select name="s_BKAG">
<option></option>
<?php $bkagbruggwert = $abc['BKAG (Brugg)']; ?>
<option value="1" <?php if($bkagbruggwert == 1) { echo 'selected'; } ?>>Ja</option>
<option value="0" <?php if($bkagbruggwert == 0) { echo 'selected'; } ?>>Nein</option>
</select>
This way, if there is no preselected value, the empty option will be displayed; if there is a preselected value and this value is same as value of any option, it will be selected.
I hope this works for you.
You can do it this way,
Assign the default value to the hidden element
In case, if the user doesn't select one option, then assign the default value from the hidden element
function fetchValue()
{
var selectedValue = document.getElementById("s_BKAG").value;
if(selectedValue == "")
{
selectedValue = document.getElementById("default-value").value;
}
console.log("The selected value is: " + selectedValue);
}
<select id="s_BKAG" name="s_BKAG">
<option value="">None</option>
<option value="1">Ja</option>
<option value="0">Nein</option>
</select>
<input id="default-value" type="hidden" value="<?php echo $abc['BKAG (Brugg)'] ?>" />
<input type="button" value = "Fetch Value" onclick="fetchValue()" />

picking selected value from dropdown on page refresh

I am creating my form and adding error handling.
When the page is refreshed i want to be able to select the previous selected value in the drop down menu but i am struggling to get this to work.
Is anyone able to help
<select value="<? echo $_POST["Bookie"][$i]?>" style="width:100px;" id="Bookie[]" name="Bookie[]">
<option>Bet365</option>
<option>Betbright</option>
<option>Betfair</option>
<option>Betfred</option>
<option>BetVictor</option>
<option>Boylesports</option>
<option>Bwin</option>
<option>Centrebet</option>
<option>Coral</option>
<option>Ladbrokes</option>
<option>Paddy Power</option>
<option>Pinnacle Sports</option>
<option>SBOBET</option>
<option>Sky Bet</option>
<option>Stan James</option>
<option>unibet</option>
<option>William Hill</option>
</select>
You have to repeat this for each <option> tag, changing Paddy Power as appropriate:
<option<?php if(!empty($_POST) && $_POST['Bookie'][$i] == 'Paddy Power') echo ' selected="selected"';?>>Paddy Power</option>
If your <form> tag has method="post", you'll be fine with the above snippet. Otherwise you'll need to change $_POST in the above to $_GET.
Also, remove value="<? echo $_POST["Bookie"][$i]?>" from your <select> tag as that attribute is not supported there. The selected attribute is for setting the selected option in a <select> list.
just use $_SESSION['convert']:
The first time you open the page you will check if session exists:
session_start();
$convert = isset($_SESSION['convert'])?$_SESSION['convert']:"Bet365";
So, when you will write your dropdown like:
<form>
<select>
<option value="Bet365" <?php echo $convert=='Betfair'?'selected':''?>>Bet365</option>
<option value="Coral" <?php echo $convert=='Coral'?'selected':''?>>Coral</option>
</select>
</form>
then on form submit you will take the actual convert selected and save it in session:
session_start();
$convert = $_POST['convert'];
$_SESSION['convert] = $convert;
last selected option after refresh the page

Get the Selected value from the Drop down box in PHP

I am populating a Drop Down Box using the following code.
<select id="select_catalog">
<?php
$array_all_catalogs = $db->get_all_catalogs();
foreach($array_all_catalogs as $array_catalog){?>
<option value="<?= $array_catalog['catalog_key'] ?>"><?= array_catalog['catalog_name'] ?></option>
Now how can I get the selected option value using PHP (I have the code to get the selected item using Javascript and jQuery) because I want the selected value to perform a query in database.
Any help will be much appreciated. Thank you very much...
You need to set a name on the <select> tag like so:
<select name="select_catalog" id="select_catalog">
You can get it in php with this:
$_POST['select_catalog'];
Couldn't you just pass the a name attribute and wrap it in a form?
<form id="form" action="do_stuff.php" method="post">
<select id="select_catalog" name="select_catalog_query">
<?php <<<INSERT THE SELECT OPTION LOOP>>> ?>
</select>
</form>
And then look for $_POST['select_catalog_query'] ?
You have to give a name attribute on your <select /> element, and then use it from the $_POST or $_GET (depending on how you transmit data) arrays in PHP. Be sure to sanitize user input, though.
Posting it from my project.
<select name="parent" id="parent"><option value="0">None</option>
<?php
$select="select=selected";
$allparent=mysql_query("select * from tbl_page_content where parent='0'");
while($parent=mysql_fetch_array($allparent))
{?>
<option value="<?= $parent['id']; ?>" <?php if( $pageDetail['parent']==$parent['id'] ) { echo($select); }?>><?= $parent['name']; ?></option>
<?php
}
?></select>

Using PHP $_POST to remember a option in a select box?

I have a form which POSTs to itselft so the user can do things that you would find in a Shopping Cart.
e.g. Increase quantity, select postage type.
My problem is for my form Select element called "postage" whenever the form reloads itself , it forgets what was selected.
All my other fields remember their values using this:
<input type="text" name="postcode" value="<?php echo $_POST['postcode']; ?> " />
How do I use the $_POST value to automatically select the option in the select field that was done by the user?
I tried this:
<select name="postage" selected="<?php echo $_POST['postage']; ?>" >
and this
<select name="postage" value="<?php echo $_POST['postage']; ?>" >
Thanks
You almost got it. You need to set the attribute selected="selected" (the exact form you need technically depends on your HTML doctype, but this is a safe default) on the <option> element if and only if the value of $postage equals the value of the element. So:
<select name="postage">
<option value="foo"
<?php if ($_POST['postage'] == "foo") echo 'selected="selected" '; ?>
>
</select>
Note that this violates the DRY principle because you now have two occurrences of the string "foo" in there, so it's a prime candidate for refactoring. A good approach would be to keep value/text pairs in an array and iterate over it with foreach to produce the <option> tags.
You need to foreach through all the options.
Make an array with all the dropdown options, loop through that, and compare with what is stored in post.
E.G.:
<?php
$aDropd = array("apple","orange","banana");
echo "<select>";
foreach($aDropd as $sOption){
$sSel = ($sOption == $_POST['postage'])? "Selected='selected'":"";
echo "<option $sSel>$sOption</option>";
}
echo "</select>";
no its not working at all..you need to put some kind of loop for that.
For Example : foreach($record => $values){
if($values == $_POST['postage']){
$selected = "selected='selected' ";
}else{
$selected = "";
}
}
<input name="postage" value="1" <?=$selected?> >
EDITED:
if($_POST['postage'] == 1){
$selected1 = "selected='selected' ";
}else if($_POST['postage'] == 2){
$selected2 = "selected='selected' ";
} and so on..........
<select name="postage">
<option value="1" <?=$selected1;?> />
<option value="2" <?=$selected2;?> />
</select>
I think this may be helpful to you..you can ask me if anything else needed...
Thanks.
The value of selected should be selected
<select name="postage" value="1" <?php echo (($_POST['postage'] == 1)?'selected="selected"':''); ?> >
Your html syntax is wrong. The correct way to write the html is like this:
<select>
<option value ="<?php echo $_POST['postage']; ?>" selected="selected"></option>
</select>
You can also make it shorter:
<select>
<option value ="<?=$_POST['postage']; ?>" selected="selected"></option>
</select>
<select name="foo">
<option value="1" <?php echo strcmp($_POST['foo'],"1")==0?"selected=\"selected\"":"" ?>>option1</option>
<option value="2" <?php echo strcmp($_POST['foo'],"2")==0?"selected=\"selected\"":"" ?>>option2</option>

Categories