Setting value of dropdown box to last submitted value with javascript - php

I have the following dropdown box
<form name="myform" method="POST" ACTION="songs.php">
Select Category: <select id="sel" name="categories" onchange="document.myform.submit()">
And all the options follow after. When the user makes a selection, the category is brought up below using PHP and MYSQl based on the selection containing a list of songs etc.
However, the dropdown box always defaults back to the first value in the list of options. How do I make so that the dropdown box will set the selected option to the last submitted value? Thanks in advance!

You can't do that with JS as it has no direct access to POST request parameters. Rather let the server side language (which is in your case PHP) print the selected attribute on the <option> element whenever the submitted value matches the option value.
E.g.
foreach ($options as $value => $label) {
echo '<option value="' . $value . '"' . ($selected == $value ? ' selected' : '') . '>' . $label . '</option>';
}

Related

Form built from database array values is not limiting radio buttons to single selection

I am trying to build a form where the user selects an item based upon an array of values from a database table. Here is the code that I am using to filter out the list:
$arrlength=count($results);
$listSubscriptions = '<form>';
for($x=0; $x<$arrlength; $x++)
{
$itemList = $results[$x]->item_name;
$listSubscriptions .= '<input type="radio" name="'.$itemList.'" value="'.$itemList.'"> '.$itemList.'<br>';
}
$listSubscriptions .= '</form>';
return $listSubscriptions;
When I print the results of the form I am able to get the radio buttons to display as I would like them to, but the problem is that the selection is not being limited to one radio button selection. Any ideas why?
The radio buttons must all share a single name attribute to belong to the same group:
$listSubscriptions .= '<input type="radio" name="subscription" value="' . $itemList . '"> ' . $itemList . '<br>';

How to make a drop down field (populated from mysql db) appear based on user selection

I have a form. The first field is a drop down select option. The user will select the name of a company. Based on the name a second drop down select option needs to be generated showing the addresses of all the company's branches.
The company data is stored in a mysql database.
How can I make the above happen?
If you are saying about <select> tag, the you can use this.
<select name="option">
<option value="one"<?php echo ($data["option"] == "one") ? ' selected="selected"' : ""; ?>>One</option>
<option value="two"<?php echo ($data["option"] == "two") ? ' selected="selected"' : ""; ?>>Two</option>
<option value="three"<?php echo ($data["option"] == "three") ? ' selected="selected"' : ""; ?>>Three</option>
</select>
For the sub select, see this demo: http://jsfiddle.net/ah4rx/
You have two options here
post the form on change of first dropdown and fetch the data based on posted value and display.
use ajax functionality to fetch the data based on value selected in dropdown and display
As basic as it gets - Send the company name via ajax to php, query the database to get the address, populate the next drop down in the same php script whilst in the loop and echo out. Receive back in ajax
I would use that code for the first generation of the first list. Then the second list would have to be done with AJAX (JQUERY can help you here).
You want JQUERY to get
var client=$('#client_name').find("option:selected");
Then make a normal AJAX request.
I would recomend you to use a PDO to connect to your databse instead of using that generic connection.
Based on the code that you posted in the reply to Vamsi then the code would be
<label>Client Name</label><br>
<select id="client_name">
<?php
// PDO connect to the DB
$db = new PDO ('mysql:host=localhost;dbname=DB_NAME','DB_USER','DB_PASS');
$sql = 'SELECT name FROM client'
$result = $db->query($sql)->fetchAll(PDO::FETCH_ASSOC);
if(count($results)>0){ echo "<option></option>";}
foreach( $result as $key => $val)
{
// could also be $val['name'] depending on your db
echo "<option>".$key['name']."</option>";
}
?>
<select>

Using PHP function to create a dynamic dropdown menu using arrays: dropdown doesn't populate

I am trying to dynamically build a drop down menu using PHP. The idea is: the elements are formed from a loop which calls and array. If the array element matches the data held in session then it adds the "selected" attribute to the tag, meaning that the page displays the previously selected option.
I have tried to include one complete set of code here, all the way from defining the variables from session data to echoing the HTML for the form element.
It doesn't currently work - the drop down menu appears, but is blank, and has no options. I've debugged it with ideone and it seemed to run successfully, and I can't see where I am going wrong, however this is my first PHP function! So I'm sure I've screwed it up somehow :)
Any help much appreciated.
<?php
session_start();
//if the session data has been set, then the variable $sv_02 is defined
//as the data held in the session under that name, otherwise it is blank
if (isset($_SESSION['sv_02'])) {$sv_02=$_SESSION['sv_02'];} else {$sv_02="";}
//define the array
$dm_sv_02 = array('-Year','-2012','-2011','-2010','-2009');
//create the function
function dropdown($dropdownoptions, $session_data)
{
foreach($dropdownoptions as $dropdownoption){
if($session_data == $dropdownoption){
echo '<option value="' . $dropdownoption . '" selected>' . $dropdownoption . '</option>';
} else {
echo '<option value="' . $dropdownoption . '">' . $dropdownoption . '</option>';
}
}
}
//echo the HTML needed to create a drop down, and populate it with
//the function which should create the <option> elements
echo '<select name="sv_02">';
dropdown($dm_sv_02, $sv_02);
echo '</select>';
?>
Try this:
foreach ($dropdownoptions as $dropdownoption) {
echo ($dropdownoption == $sv_02) ? "<option selected=\"selected\" value=\"$dropdownoption\">$dropdownoption</option>" : "<option value=\"$dropdownoption\">$dropdownoption</option>";}
This turned out to be a result of the fact I was using {smarty} tags to build my php, the code was as written but only worked when it was all included in one smarty tag, I'm not sure I understand why that should be the case but in any regard it was fixed by including it all in one tag.

PHP Form Error Validation

I'm working on a php form with some validation rules.
If some of the fields are left blank that are require the form will report and error message and ask the user to complete the field.
The form currently keeps the values of the $_POST data so that if errors occur the data which is in the field remains.
I am having a problem with two fields(drop down lists) which are populated with data from a database.
If I complete these fields but there is a error elsewhere the form displays with the values in the drop down list but when I correct the errors and try submit the form it tells me that the drop down list fields are empty.
Here is the code for them
<! Drop Down Menu to get student names from database !>
<SELECT NAME=studentName >
<OPTION VALUE=0 selected="selected" >
<?php if(isset($_POST['studentName'])) echo $_POST['studentName'];?>
<?php echo $options1?>
</SELECT>
Any idea's why this is happening?
For starters, <option value=0 selected="selected"> means that option 0 will always be selected.
You could do something like the following, excuse me if this snippet has bugs, but it should give you a general idea of how you could achieve what you want to:
<?php
$myOptions = array(
'0' => ' --- nothing selected ---',
'1' => 'Apples',
'2' => 'Bananas',
// ...
);
?>
<select name="studentName">
<? php
foreach($myOptions as $key => $value ) {
$selected = isset($_POST['theOption']) && $_POST['theOption'] == $key ? 'selected="selected"' : "";
echo '<option value="' . $key . '" '. $selected . '>' . $value . "</option>";
}
?>
</select>
You can cleanup the above a bit using the alternative PHP syntax:
http://php.net/manual/en/control-structures.alternative-syntax.php
This isn't part of your bug, but just a good practice consideration, some of your HTML tags and their attributes are uppercase, and it's common nowadays to use lowercase. It's more standard this way.
You shouldn't echo $_POST['studentName']; you should check it against the value of each of your options (which should be an array in PHP, which you convert to a list of <option>s in a foreach loop), and set the selected attribute if it matches.
On a sidenote, your HTML is invalid; some attributes are not quoted, and a comment should be in <!-- ... -->, not <! ... !>.

Keep a Select Box Selected after Submit

On my website, user's are allowed to filter games by Genre. When a user chooses a genre from the select box and hits submit, the page uses GET to see what the filter was. Now the filter works fine, the problem is that the select box's selection goes to the default one (Which says "All".)
I want it so that after a user submits their filter request, the select box will keep that selection after the page reloads.
There's only one way I could think of to do this but it would require adding in PHP into every option there is. Are there any simpler ways to go about doing this with PHP or jQuery?
You don't want to do this with jQuery. There it is not for.
Just have the options in an array in PHP and loop over it. If the looped value matches the currently selected option, then just add the selected attribute.
E.g.
foreach ($options as $value => $label) {
echo '<option value="' . $value . '" ' . ($selected == $value ? ' selected' : '') . '>' . $label . '</option>';
}
Assuming you're doing a full form submit the selected option is only going to be available to the server-side code, once it gets back to the client to use jQuery you won't have that (unless you try to use cookies before the form submit, but bleh).
I'd use PHP in the option tag and echo selected="selected" if the option matches up with the selected option.
If you want to avoid a lot of duplicated code why not do something like this:
<select name="test">
<?php
$options = array(1 => 'Option 1', 2 => 'Option 2', 3 => 'Option 3');
foreach ($options as $key => $value) {
echo '<option value="' . $key . '"' . ($key == $_GET["test"] ? ' selected="selected"' : '') . '>' . $value . '</option>';
} ?>
</select>
you can do it without a loop just change the 6 to whatever value you want when you render the page
$("#$optionId[value=6]").attr('selected','selected');

Categories