This question already has answers here:
Using $_POST to get select option value from HTML
(8 answers)
Closed 6 years ago.
I am trying to get the option selected using PHP, but I ran out of ideas!
Below is the code I have tried until now:
<select>
<option value="1">Yes</options>
<option value="2">No</options>
<option value="3">Fine</options>
</select>
<input type="text" value="" name="name">
<input type="submit" value="go" name="go">
So, what do I have to do?
Programmers are lazy...er....efficient....I'd do it like so:
<select><?php
$the_key = 1; // or whatever you want
foreach(array(
1 => 'Yes',
2 => 'No',
3 => 'Fine',
) as $key => $val){
?><option value="<?php echo $key; ?>"<?php
if($key==$the_key)echo ' selected="selected"';
?>><?php echo $val; ?></option><?php
}
?></select>
<input type="text" value="" name="name">
<input type="submit" value="go" name="go">
<select>
<option value="1" <?php if ($myVar==1) echo 'selected="selected"';?>>Yes</options>
<option value="2" <?php if ($myVar==2) echo 'selected="selected"';?>>No</options>
<option value="3" <?php if ($myVar==3) echo 'selected="selected"';?>>Fine</options>
</select>
<input type="text" value="" name="name">
<input type="submit" value="go" name="go">
This is a very simple and straightforward way, if I understand your question correctly.
you can use this..
<select name="select_name">
<option value="1"<?php echo(isset($_POST['select_name'])&&($_POST['select_name']=='1')?' selected="selected"':'');?>>Yes</option>
<option value="2"<?php echo(isset($_POST['select_name'])&&($_POST['select_name']=='2')?' selected="selected"':'');?>>No</option>
<option value="3"<?php echo(isset($_POST['select_name'])&&($_POST['select_name']=='3')?' selected="selected"':'');?>>Fine</option>
</select>
First of all give a name to your select. Then do:
<select name="my_select">
<option value="1" <?= ($_POST['my_select'] == "1")? "selected":"";?>>Yes</options>
<option value="2" <?= ($_POST['my_select'] == "2")? "selected":"";?>>No</options>
<option value="3" <?= ($_POST['my_select'] == "3")? "selected":"";?>>Fine</options>
</select>
What that does is check if what was selected is the same for each and when its found echo "selected".
I suppose that you are using an array to create your select form input.
In that case, use an array:
<?php
$selected = array( $_REQUEST['yesnofine'] => 'selected="selected"' );
$fields = array(1 => 'Yes', 2 => 'No', 3 => 'Fine');
?>
<select name=‘yesnofine'>
<?php foreach ($fields as $k => $v): ?>
<option value="<?php echo $k;?>" <?php #print($selected[$k]);?>><?php echo $v;?></options>
<?php endforeach; ?>
</select>
If not, you may just unroll the above loop, and still use an array.
<option value="1" <?php #print($selected[$k]);?>>Yes</options>
<option value="2" <?php #print($selected[$k]);?>>No</options>
<option value="3" <?php #print($selected[$k]);?>>Fine</options>
Notes that I don't know:
how you are naming your input, so I made up a name for it.
which way you are handling your form input on server side, I used $_REQUEST,
You will have to adapt the code to match requirements of the framework you are using, if any.
Also, it is customary in many frameworks to use the alternative syntax in view dedicated scripts.
I use inline if's
($_POST['category'] == $data['id'] ? 'selected="selected"' : false)
I have 2 php files and i made this, and it works.
(this is an example) the first code is from the one file and the second code from two file.
<form action="two.php" method="post">
<input type="submit" class="button" value="submit" name="one"/>
<select name="numbers">
<option value="1"> 1 </option>
<option value="2"> 2 </option>
<option value="3"> 3 </option>
</select>
</form>
if(isset ($_POST['one']))
{
if($_POST['numbers']=='1')
{
$a='1' ;
}
else if($_POST['numbers']=='2')
{
$a='2' ;
{
else if ($_POST['numbers']=='3')
{
$a='3' ;
}
}
This answer is not relevant for particular recepient, but maybe useful for others.
I had similiar issue with 'selecting' right 'option' by value returned from database.
I solved it by adding additional tag with applied display:none.
<?php
$status = "NOT_ON_LIST";
$text = "<html>
<head>
</head>
<body>
<select id=\"statuses\">
<option value=\"status\" selected=\"selected\" style=\"display:none\">$status</option>
<option value=\"status\">OK</option>
<option value=\"status\">DOWN</option>
<option value=\"status\">UNKNOWN</option>
</select>
</body>
</html>";
print $text;
?>
This is the solution that I've came up with:
<form name = "form1" id = "form1" action = "#" method = "post">
<select name = "DropDownList1" id = "DropDownList1">
<?php
$arr = array('Yes', 'No', 'Fine' ); // create array so looping is easier
for( $i = 1; $i <= 3; $i++ ) // loop starts at first value and ends at last value
{
$selected = ''; // keep selected at nothing
if( isset( $_POST['go'] ) ) // check if form was submitted
{
if( $_POST['DropDownList1'] == $i ) // if the value of the dropdownlist is equal to the looped variable
{
$selected = 'selected = "selected"'; // if is equal, set selected = "selected"
}
}
// note: if value is not equal, selected stays defaulted to nothing as explained earlier
echo '<option value = "' . $i . '"' . $selected . '>' . $arr[$i] . '</option>'; // echo the option element to the page using the $selected variable
}
?>
</select> <!-- finish the form in html -->
<input type="text" value="" name="name">
<input type="submit" value="go" name="go">
</form>
The code I have works as long as the values are integers in some numeric order ( ascending or descending ). What it does is starts the dropdownlist in html, and adds each option element in php code. It will not work if you have random values though, i.e: 1, 4, 2, 7, 6. Each value must be unique.
Related
I'm having a hard time to fix and how can make my codes work well.
My textbox echo correctly while my dropdown box is not.
Can anyone help me and also clean my codes?
I wanna know how did you do it and can u please explain it to me.
Thank you so much.
index.php
<?php include 'test.php' ?>
<form method="post" action="index.php">
Textbox: <input type="text" name="txt1" value="<?php echo $txt1;?>">
Dropdown: <select name="drpdown1" value="<?php echo $drpdown1;?>">
<option></option>
<option value="1">Mark</option>
<option value="2">Extreme</option>
</select>
<input type="submit" name="btn1">
</form>
test.php
<?php
$txt1 = "";
$drpdown1 = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$txt1 = $_POST["txt1"];
$drpdown1 = $_POST["drpdown1"];
}
?>
You're not echoing the value of $drpdown1 correctly:
// this is wrong for a select:
<select name="drpdown1" value="<?php echo $drpdown1;?>">
// etc.
If you want to select automatically the previously selected value, you need to add the selected attribute:
<select name="drpdown1">
<option value="1" <?php if ($drpdown1 === '1') { echo "selected='selected'"; } ?>>Mark</option>
<option value="2" <?php if ($drpdown1 === '2') { echo "selected='selected'"; } ?>>Extreme</option>
// etc.
you have to know more about the dropdown box because you can not put the value inside the
<select value="<?php echo $drpdown1;?>">
you have to compare the value inside the option directly. example
<select name="drpdown1">
<?php
if($drpdown1 == ""){
?>
<option selected></option>
<option value="1">Mark</option>
<option value="2">Extreme</option>
<?php
}else if($drpdown1 == "1"){
?>
<option></option>
<option value="1" selected>Mark</option>
<option value="2">Extreme</option>
<?php
}
?>
</select>
I have this following codes.How do i send this form to php so in php i can access it like studentName course2 year3.Basically i have a table which looks like this studentName|course|year.I am looking for the right way to organize the data in order to insert it to my table.I have tried sending the form not as an array but i have to write 3 queries to insert 3 inputs.Is there any way to loop through the data and insert?
<form id="myform" method="POST">
<label>college:</label><input type="text" id="clg" name="clg"/><br/>
<label>Student:-</label><input type="text" name="name[]" id="name" />
<select name="taskOpen[]">
<option value="1">course1</option>
<option value="2">course2</option>
<option value="3">course3</option>
<option value="4">course4</option>
</select>
<select name="year[]">
<option value="1">year1</option>
<option value="2">year2</option>
<option value="3">year3</option>
<option value="4">year4</option>
</select>
<label>Student:-</label><input type="text" name="name[]" id="name" />
<select name="taskOpen[]">
<option value="1">course1</option>
<option value="2">course2</option>
<option value="3">course3</option>
<option value="4">course4</option>
</select>
<select name="year[]">
<option value="1">year1</option>
<option value="2">year2</option>
<option value="3">year3</option>
<option value="4">year4</option>
</select>
<input type="button" value="search" id="btn"/>
</form>
Here is what i have in php--
if(isset($_POST['name']) && isset($_POST['taskOpen'])
&& isset($_POST(['year'])){
$name=$_POST['name'],$course=$_POST['taskOpen'],$year=$_POST['year']
}
else {
echo "something";
}
foreach($name as $student){
$sql=$conn->prepare("INSERT INTO `student`(`studentName`) VALUES(:s_n)");
$sql->execute(array(":s_n"=>$student));
}
foreach($course as $courseN){
$sql=$conn->prepare("INSERT INTO `student`(`course`) VALUES(:co)");
$sql->execute(array(":co"=>$courseN));
}
foreach($year as $yearD){
$sql=$conn->prepare("INSERT INTO `student`(`year`) VALUES(:ya)");
$sql->execute(array(":ya"=>$yearD));
}
Here is what i think you are going for...
HTML
<!-- THE NAMES OF INPUT ELEMENTS WRAPPED IN A college_data-->
<form id="myform" method="POST">
<label>college:</label><input type="text" id="clg" name="college_data[clg]"/><br/>
<label>Student:-</label><input type="text" name="college_data[name]" id="name"/>
<select name="college_data[taskOpen1]">
<option value="1">course1</option>
<option value="2">course2</option>
<option value="3">course3</option>
<option value="4">course4</option>
</select>
<select name="college_data[year1]">
<option value="1">year1</option>
<option value="2">year2</option>
<option value="3">year3</option>
<option value="4">year4</option>
</select>
<label>Student:-</label><input type="text" name="name[]" id="name"/>
<select name="college_data[taskOpen2]">
<option value="1">course1</option>
<option value="2">course2</option>
<option value="3">course3</option>
<option value="4">course4</option>
</select>
<select name="college_data[year2]">
<option value="1">year1</option>
<option value="2">year2</option>
<option value="3">year3</option>
<option value="4">year4</option>
</select>
<input type="submit" value="search" id="btn"/>
</form>
PHP
<?php
$college = isset($_POST['college_data']['clg']) ? htmlspecialchars(trim($_POST['college_data']['clg'])) :null;
$studentName = isset($_POST['college_data']['name']) ? htmlspecialchars(trim($_POST['college_data']['name'])) :null;
$studentName2 = isset($_POST['college_data']['name2']) ? htmlspecialchars(trim($_POST['college_data']['name2'])) :null;
$taskOpen1 = isset($_POST['college_data']['taskOpen1']) ? htmlspecialchars(trim($_POST['college_data']['taskOpen1'])) :null;
$taskOpen2 = isset($_POST['college_data']['taskOpen2']) ? htmlspecialchars(trim($_POST['college_data']['taskOpen2'])) :null;
$year1 = isset($_POST['college_data']['year1']) ? htmlspecialchars(trim($_POST['college_data']['year1'])) :null;
$year2 = isset($_POST['college_data']['year2']) ? htmlspecialchars(trim($_POST['college_data']['year2'])) :null;
// TEST::: DELETE EVERYTHING BELOW THIS LINE ONCE YOU ARE DONE CONFIRMING THAT IT IS OK
// CLICK THE SUBMIT BUTTON TO SEE THE VALUES REFLECTED HERE AS SOON AS THE FORM GETS SUBMITTED...
var_dump($college);
var_dump($studentName);
var_dump($studentName2);
var_dump($taskOpen1);
var_dump($taskOpen2);
var_dump($year1);
var_dump($year2);
?>
VALIDATION
<?php
// FIRST CREATE AN ARRAY TO HOLD MESSAGES TO BE SHOWN TO THE USER
// SHOULD ANYTHING GO WRONG... & ALSO AN EMPTY ERROR MESSAGE STRING...
$arrErrorBag = array();
$strErrorMsg = "";
if(isset($_POST['submit'])) {
// LET'S ASSUME FOR THE MOMENT YOU HAVE SPECIAL CONSTRAINTS
// TO BE APPLIED TO EACH FIELD DURING YOUR VALIDATION PROCESS.
// WE WILL USE SIMPLE REGULAR EXPRESSIONS HERE FOR DEMONSTRATION
// BUILD VALIDATION REG-EXES FOR THE FIELD:: WE WANT ONLY A MINIMUM OF 10 CHARACTERS FOR STUDENT & COLLEGE
// AGAIN; YOU CAN GO WILD BUT WE ARE KEEPING IT SIMPLE
// PLUS, DOING IT LIKE THIS IS JUST SO THAT YOU GET THE DRIFT... ;-)
$rxColStudent = "#(.){10,}#si";
// FOR THE SELECTS, WE KNOW THAT THE VALUES ARE NUMBERS
// WHICH ARE BETWEEN 1 & 4; BUT WE TAKE IT TO "BETWEEN 1 & 9"
// AND WE INTEND USING ONE REGEX FOR ALL OF THEM SINCE THEY ARE SIMILAR.
$rxCourseYear = "#\d#";
// NOW WE HAVE THE REGEXES: THEN WHAT?
// VALIDATION BEGINS... ;-)
// TO MAKE IT EASIER ON OURSELVES, WE BUNDLE ALL THE STUDENT, STUDENT1 & COLLEGE FIELDS
// INTO AN ARRAY & LOOP THROUGH THE ARRAY, BUILDING THE ERRORS ON EACH ITERATION THROUGH THE LOOP.
// VALIDATE COLLEGE, STUDENT & STUDENT2...
$arrStringValFields = array(
"student" => array("Student Nr. 1", $studentName),
"student2" => array("Student Nr. 2 ", $studentName2),
"college" => array("College", $college),
);
// RUN THE LOOP & KEEP BUILDING THE ERRORS AS YOU VALIDATE THROUGH EACH ITERATION.
foreach ($arrStringValFields as $fieldName => $arrErrStringVal) {
if (!preg_match($rxColStudent, $arrErrStringVal[1])) {
$arrErrorBag[$fieldName] = $arrErrStringVal[0] . " is expected to have a minimum of 10 Characters. Please, check that you have not missed something.";
}
}
// TO MAKE IT AGAIN EASIER ON OURSELVES, WE BUNDLE ALL OTHER FIELDS THAT HAVE NUMERIC VALUES
// INTO AN ARRAY & LOOP THROUGH THE ARRAY, BUILDING THE ERRORS ON EACH ITERATION THROUGH THE LOOP.
$arrNumericFields = array(
"taskOpen1" => array("Open Task Nr. 1", $taskOpen1),
"taskOpen2" => array("Open Task Nr. 2 ", $taskOpen2),
"year1" => array("College Year Section 1", $year1),
"year2" => array("College Year Section 2", $year2),
);
// RUN THE LOOP & KEEP BUILDING THE ERRORS AS YOU VALIDATE THROUGH EACH ITERATION.
foreach ($arrNumericFields as $fieldName => $arrErrStringVal) {
if (!preg_match($rxCourseYear, $arrErrStringVal[1])) {
$arrErrorBag[$fieldName] = $arrErrStringVal[0] . " is expected to be a Single Digit & it should. Did you try to *NUKE OUR ASSES OFF*. Please, don't. We are your Brothers ;-)";
}
}
// MAMA MIA!!! SO MUCH FOR A SIMPLE 6-FIELD VALIDATION...
// HAPPILY ENOUGH; WE ARE THERE... ONLY; NOT JUST YET...
// CHECK THE ERROR BAG TO SEE IF IT CONTAINS ANYTHING.
// IF IT DOES; THEN WE HAVE TO FIND A WAY TO DISPLAY THIS TO THE END-USER.
if (!empty($arrErrorBag)) {
// TURN THE ERROR BAG ARRAY TO A STRING & ASSIGN IT BACK TO THE ERROR MESSAGE STRING FOR DISPLAY...
$strErrorMsg = "<span class='has-error'>" . implode("</span><br /><span class='has-error'>", $arrErrorBag);
}
else {
// WE HAVE REACHED THE CLIMAX OF OUR POLICE-WORK...
// SO WE EITHER STORE THE DATA TO THE DATABASE TABLE OR
// WE BAKE & CAKE IT FOR CHRISTMAS - YOUR CALL ;-)
}
}
?>
Now, that's OK. But how does the User get to know that there were Errors and how does s/he avoid typing-in the same information over again?
Our HTML File should have been built earlier to take that into consideration, but then again, EINTEIN WAS RIGHT!!! Human Stupidity is totally as Infinite as the Universe... but that's why we are here, right? To cut down the infinitude of our Stupidity and grow into real Humans;-) So we revise our HTML to take these into account.
HTML - REVISED: UNLEASH THE DRAGON!!!
<!-- WE ADD A SLOT FOR OUR ERROR MESSAGE: JUST BEFORE THE FORM. -->
<div class="error-slot"><?php echo $strErrorMsg; ?></div>
<form id="myform" method="POST">
<label>college:</label><input type="text" id="clg" name="college_data[clg]" value="<?php echo $college; ?>" /><br/>
<label>Student:-</label><input type="text" name="college_data[name]" value="<?php echo $studentName; ?>" id="name"/>
<select name="college_data[taskOpen1]">
<option value="1" <?php if($taskOpen1=="1"){echo "selected";} ?>>course1</option>
<option value="2" <?php if($taskOpen1=="2"){echo "selected";} ?>>course2</option>
<option value="3" <?php if($taskOpen1=="3"){echo "selected";} ?>>course3</option>
<option value="4" <?php if($taskOpen1=="4"){echo "selected";} ?>>course4</option>
</select>
<select name="college_data[year1]">
<option value="1" <?php if($year1=="1"){echo "selected";} ?>>year1</option>
<option value="2" <?php if($year1=="2"){echo "selected";} ?>>year2</option>
<option value="3" <?php if($year1=="3"){echo "selected";} ?>>year3</option>
<option value="4" <?php if($year1=="4"){echo "selected";} ?>>year4</option>
</select>
<label>Student:-</label><input type="text" name="college_data[name2]" value="<?php echo $studentName2; ?>" id="name"/>
<select name="college_data[taskOpen2]">
<option value="1" <?php if($taskOpen2=="1"){echo "selected";} ?>>course1</option>
<option value="2" <?php if($taskOpen2=="2"){echo "selected";} ?>>course2</option>
<option value="3" <?php if($taskOpen2=="3"){echo "selected";} ?>>course3</option>
<option value="4" <?php if($taskOpen2=="4"){echo "selected";} ?>>course4</option>
</select>
<select name="college_data[year2]">
<option value="1" <?php if($year2=="1"){echo "selected";} ?>>year1</option>
<option value="2" <?php if($year2=="2"){echo "selected";} ?>>year2</option>
<option value="3" <?php if($year2=="3"){echo "selected";} ?>>year3</option>
<option value="4" <?php if($year2=="4"){echo "selected";} ?>>year4</option>
</select>
<input type="submit" value="search" name="submit" id="btn"/>
</form>
From your table design in the database it looks like you want to insert a student, their course and the year they are taking it in. Unless you are going to validate the form so that the number of students matches the number of courses and numbers of years so you can easily loop and insert based on their indexes, i don't see how it can be easily done.
Example:
$_POST = Array(
'name' = Array ( 'Kelly', 'Tom', 'Jack' ),
'course' = Array ( 'Course1', 'Course2', 'Course3' ),
'year' = Array ( '2007', '2008', '2009' ),
);
for ( $i = 0; i < count($_POST['student_name']); i++ ) {
$sql = sprintf("INSERT INTO test ( student_name, course, year ) VALUES ( %s, %s, %d )",
$_POST['student_name'][$i], $_POST['course'][$i], $_POST['year'][$i]
);
$conn->query($sql);
}
Is there a way to get the previous value of select option?
the previous value is Red
If i change it to green it will echo the selected color
How can i echo the previous color which is red?
this is my code : thanks :)
<form action="#" method="post">
<select name="Color">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
<option value="Pink">Pink</option>
<option value="Yellow">Yellow</option>
</select>
<input type="submit" name="submit" value="Get Selected Values" />
</form>
<?php
if(isset($_POST['submit'])){
$selected_val = $_POST['Color'];
echo "You have selected :" .$selected_val . "<p>";
echo "The previous value is :" ;
}
?>
Use hidden field to store current value. On form post, check if the current value is different than selected value show it.
Pro tip: Always encrypt your hidden field data
store the previous value in your form as hidden value and get it
<?php
if(isset($_POST['submit'])){
$selected_val = $_POST['Color'];
$previous = $_POST['previous'];
}
?>
<form action="#" method="post">
<select name="Color">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
<option value="Pink">Pink</option>
<option value="Yellow">Yellow</option>
</select>
<input type="hidden" name="previous" value="<?php echo $selected_val; ?>"/>
<input type="submit" name="submit" value="Get Selected Values" />
</form>
<?php echo "You have selected :" .$selected_val . "<p>";
echo "The previous value is :".$previous ; ?>
Since you must never trust user submitted content, another way is to build your form from PHP and do the test on the server side.
Example:
<?php
$colors = Array('Red', 'Green', 'Blue', 'Pink', 'Yellow');
?>
<form method="POST">
<select name="Color"><?php
foreach($colors as $color)
{
printf(' <option value="%1$s">%1$s</option>'."\n", $color);
}
?>
</select>
<input type="submit">
</form>
<?php
if (!empty($_POST['Color']))
{
$previous_index = array_search($_POST['Color'], $colors) - 1;
// wrap around if the color is the first
if ($previous_index < 0) {
$previous_index = count($colors);
}
printf(
"You have selected <q>%s</q>, the previous value is: %s\n",
$_POST['Color'],
$colors[ $previous_index ]
);
}
?>
The code is obviously longer than it could for educative purpose.
Here is another solution using jQuery, as a bonus you keep track of whole history and not just previous selection.
I have not tested the PHP part, but you get the idea.
HTML
<form action="#" method="post">
<select name="Color" onChange="updateHistory(this);">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
<option value="Pink">Pink</option>
<option value="Yellow">Yellow</option>
</select>
<input type="hidden" id="history" name="history" value="">
</div>
</div>
<input type="submit" name="submit" value="Get Selected Values" />
</form>
<?php
if(isset($_POST['submit'])){
$selected_val = $_POST['Color'];
$hist = explode(',',$_POST['history']);
// pop the last value, which is current selection
array_pop($hist);
// get the last value, which now is previous
$last_valaue = end($hist);
echo "You have selected :" .$selected_val . "<p>";
echo "The previous value is :" . $last_valaue ;
echo 'DEBUG:<br>';
var_dump($hist);
}
?>
JS
function updateHistory(el){
var val = $(el).val();
var hist = $('#history').val();
if (hist.length > 0) {hist += ','}
hist += val;
$('#history').val(hist);
}
Example JS Fiddle
UPDATE 1:
You can further manipulate history array in PHP to your needs, for example, if you need unique values, you can use array_unique() (http://php.net/manual/en/function.array-unique.php)
i have a main page that i used in uploading tickets to db, i have Select field that i want to retain the value that the user selected prior to submitting the form but its not happening...
here is my code for select field:
<select name="XiD" id="XiD">
<option value="Blank" selected="selected">Please Select...</option>
<option value="AAA">AAA</option>
<option value="BBB">BBB</option>
<option value="CCC">CCC</option>
<option value="DDD">DDD</option>
<option value="EEE">EEE</option>
<option value="FFF">FFF</option>
</select>
just to add, this Xid is being posted prior to submitting
$XiD = $_POST['XiD'];
and i try to use this script:
UPDATE - changed from $_GET to $_POST but still not working...
<script type="text/javascript">
document.getElementById('XiD').value = "<?php echo $_POST['XiD'];?>";
</script>
my jquery version im using: jquery-ui-1.10.2 and jquery-1.9.1
Use jQuery like this.
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('select#XiD').val('<?php echo $_POST['XiD'];?>');
});
</script>
You are using PHP to generate HTML. There's absolutely no need to use a third language to dictate how that HTML should be!
<select name="XiD" id="XiD">
<option value="Blank"<?=$XiD=='Blank' ? ' selected="selected"' : ''?>>Please Select...</option>
<option value="AAA"<?=$XiD=='AAA' ? ' selected="selected"' : ''?>>AAA</option>
...
</select>
Or, even better, simplify your code with an array and avoid writing duplicate code that's hard to maintain:
<?php
$options = array(
'Blank' => 'Please Select...',
'AAA' => 'AAA',
'BBB' => 'BBB',
'CCC' => 'CCC',
'DDD' => 'DDD',
'EEE' => 'EEE',
'FFF' => 'FFF',
);
<select name="XiD" id="XiD">
<?php foreach(options as $k => $v){ ?>
<option value="Blank"<?php echo $XiD==$k ? ' selected="selected"' : ''?>>Please Select...</option>
<? } ?>
</select>
According to your problem, it seems like you are using POST method (because you are getting value to $XiD = $_POST['XiD'];) and using GET to retrieve value.
So, use document.getElementById('XiD').value = "<?php echo $_POST['XiD'];?>";
instead of
document.getElementById('XiD').value = "<?php echo $_GET['XiD'];?>";
I would create a function to check if the current GET value is the same as the option in the list and in that case, return the needed attribute to make it selected by default, which is selected="selected".
This should work:
<?php
function isSelected($value){
if($value == $_GET['XiD']){
return 'selected="selected"';
}else{
return '';
}
}
?>
<select name="XiD" id="XiD">
<option value="Blank" <? echo isSelected('Blank');?>>Please Select...</option>
<option value="AAA" <? echo isSelected('AAA');?>>AAA</option>
<option value="BBB" <? echo isSelected('BBB');?>>BBB</option>
<option value="CCC" <? echo isSelected('CCC');?>>CCC</option>
<option value="DDD" <? echo isSelected('DDD');?>>DDD</option>
<option value="EEE" <? echo isSelected('EEE');?>>EEE</option>
<option value="FFF" <? echo isSelected('FFF');?>>FFF</option>
</select>
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>
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>