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>
Related
I have a form with several input fields plus a select element that has several dropdown options. The user fills in the input fields and selects one of the drop down options and submits the form. The php handler for the form saves the form inputs in a database and builds a page from these inputs. An edit link on the built page returns to the form page with the fields preset to what they were the last time the form was submitted, so the editing can start from the last state submitted.
Presetting the input fields is easy, where I can just specify value=<?php echo [saved value from last submission];?> But presetting the select element to the last value chosen is not so easy. I know that jQuery has $('select#id').val("4"); which will preset the select#id element to option #4, but how can I trigger this when the form page is loaded again? Presettng the inputs by setting value= doesn't seem to generate anything that can be sensed by jQuery.
Thanks for any ideas.
Set the attribute selected for one of the options you want to be the selected. So, something like <option <?php echo 'selected="selected"';?>>4</option>.
Edit:
Either you can generate the options in a loop having the values in an array, checking each iteration if the current option was the one that was selected by the user and set the selected attribute of that one option, or you can just use the following, although not so elegant, approach:
<select name="number">
<option value="1" <?php echo ($_POST['number'] == '1') ? 'selected="selected"' : ''; ?>>1</option>
<option value="2" <?php echo ($_POST['number'] == '2') ? 'selected="selected"' : ''; ?>>2</option>
<option value="3" <?php echo ($_POST['number'] == '3') ? 'selected="selected"' : ''; ?>>3</option>
<option value="4" <?php echo ($_POST['number'] == '4') ? 'selected="selected"' : ''; ?>>4</option>
</select>
user2570380:
I think your edited solution would work so I gave you credit. But I've found another way that works that may be even more elegant. In the HTML of my PHP file I've placed at the bottom:
<script>
jQuery('select#age_group').val(<?php echo $age_group?>);
</script>
</body>
Here select#age_group is the select element I want to preset and $age_group is the value coming into PHP that I want to set into the select element.
<label>Country <font color="8AC007">*</font> </label></td>
<td><select name="country" onchange="print_state('state',this.selectedIndex);" id="country"<?php
$sel_country = $myform->value('country');
if (isset($sel_country)) echo 'selected="selected"'; ?> />
<option value="<?php $myform->value("country"); ?>"/>Select country</option>
</select><br><?php $sel_country.'sample' ?>
<span class="error"><?php echo $myform->error("country"); ?></span>
I want to get hold with the country selected value when I submit form, instead filling the form from starting again. Here is the code Iam trying to get countries from a js file.
Apperciate your help
HTTP is stateless, so you have to put a little effort on keeping data around when moving from page to page. Seeing this as being a form with inputs (select in this case), you can use $_POST to get hold of your submitted value in the next page.
In this case you'd use $_POST['country']. If you want to keep the current form filled next time the page refreshes, make the form submit to the current page, then you'll have access to that value in $_POST.
Other ways to keep data around:
Sessions
Cookies
Database storage
But this require a little bit of additional coding in PHP.
<select name="country" onchange="print_state('state',this.selectedIndex);" id="country"/>
<option <?php if($youroldval==$myform->value('country')){ echo 'selected="selected"'; } ?> value="<?php echo $myform->value("country"); ?>"/><?php echo $myform->value("country"); ?></option>
</select>
You must store your old value of form
Ok, if I am right you should do it as follows.
If you are posting your page to the server. You have the selected value. You store this and return this page. In that case I added bollow code and added $isSelected to the code. Normally it emtpy, but if the value is equal to the selected then you set selected='selected'.
<select name="country">
<?php
$countryList = array("USA", "UK", "France", "Germany", "India", "Netherlands");
$isSelected = "";
foreach($countryList as $country)
{
if($_POST["country"] == $country)
{
$isSelected = "selected='selected'";
}
echo "<option value='" + $country + "' " + $isSelected + ">" + $country + "</option>";
?>
</select>
If you are using jquery / Ajax, you have the selected value which stays selected because the page wont refresh :-) However, you can get the value by using javascript and get value from selectbox.
------ Edit
Mmm ok, I was in the illusion you had your array in php. However you get your collection from javascript. In that case you will get this as solution:
<script type="text/javascript">
var selectedCountry = "<?php echo $myform->value("country"); ?>";
</script>
<select name="country" onchange="print_state('state',this.selectedIndex);" id="country">
/* This is generated by javascript */
</select>
Your javascript function will be like this:
function print_country(country_id){
// given the id of the <select> tag as function argument, it inserts <option> tags
var option_str = document.getElementById(country_id);
option_str.length=0;
option_str.options[0] = new Option('Select Country','');
option_str.selectedIndex = 0;
for (var i=0; i<country_arr.length; i++) {
option_str.options[option_str.length] = new Option(country_arr[i],country_arr[i]);
if(selectedCountry == country_arr[i])
{
option_str.options[option_str.length].setAttribute("selected", "selected");
}
}
}
----- Edit 2:
http://jsfiddle.net/eLProva/5mU76/ with filling and selecting the country
I have html form which is saving some data to mysql database. Now I want to create an edit page for that form which will return data from mysql database to form fields for editing and then update.
In html form i have some input fields which are disabled by default until dropdown menu is set to for example 'Yes'. When the dropdown menu option is set to yes, input field gets enabled.
I created that in jquery and it looks like this:
$(document).ready(function() {
$('#lijecnickipregled').change(function(){
if($('#lijecnickipregled').val() === 'YES')
{
$("#lijecnicki").prop('disabled',false);
}
else
{
$( "#lijecnicki" ).attr( "disabled", "disabled" );
}
});
});
Now when I'm creating edit page I managed to return value from database to dropdown menu and it is set to YES, but input field with ID "lijecnicki" is still disabled for editing until I choose some other option in dropdown menu and then put it back on YES.
Here is the HTML code of dropdown menu:
<div class="fitem" >
<label>Liječnički pregled</label>
<select name="Lijecnicki" id="lijecnickipregled">
<option value="" selected="selected"></option>
<option value="YES">YES</option>
<option value="NO">NO</option>
</select>
</div>
HTML code of input field which is being enabled when dropdown option is set to YES:
<div class="fitem" id="datumzadnjeglijecnickogpregleda" >
<label>Datum zadnjeg lijecnickog pregleda</label>
<input name="DatumZadnjegLijecnickogPregleda" id="lijecnicki" type="text" class="lijecnicki" disabled/>
</div>
And here is PHP code on edit page:
<div class="fitem" >
<label>Liječnički pregled</label>
<select name="Lijecnicki" id="lijecnickipregled">
<option value="" selected="selected"></option>
<?php
$LijecnickiPregled = array(
'YES',
'NO',
);
$lp = $s['Lijecnicki'];
?>
<?php foreach ($LijecnickiPregled as $pregled): ?>
<option <?php echo $lp == $pregled ? 'selected="selected"' : '' ?> value="<?php echo $pregled ?>"><?php echo $pregled ?></option>
<?php endforeach ?>
</select>
</div>
You are only checking the value of lijecnickipregled when it changes; you should be checking it at load time.
I am using a chained select-menu to guide the visitor trough some questions. This works like a charm, however, in the end the user has to click a button to send all values to a PHP-script. This also works without a problem, however, when the page reloads (because the button sends the form to the same page), all fields are hidden again and this is not what i want.
I would like the chained selection menu's to be shown when items in them are "selected" when the page reloads. Using PHP i simply test if a field was selected and add that status to the select-menu. But they remain hidden until you manually select everything again.
I think it's just a minor adjustment in the JS-part. But my limited knowledge of JS leaves me without a solution.
Sources
jsFiddle
Chainedselection script
jQuery UI and selectmenu
Since the form submits to itself the values the user chose will be available in either $_GET or $_POST (depending on whether the action of your form is get or post).
The best approach would then be to use those values to set the selected attribute on the appropriate <option> node using something like this.
$selectedC1Value = '';
<? if isset($_POST['c1']) { ?>
$selectedC1Value = $_POST['c1'];
<? } ?>
<select name="c1" id="c1" >
<option value="" <? if ($selectedC1Value == '') { echo 'selected'; } ?>>
--
</option>
<option value="age" <? if ($selectedC1Value == '') { echo 'selected'; } ?>>
Age
</option>
<option value="education" <? if ($selectedC1Value == '') { echo 'selected'; } ?>>
Education
</option>
<!-- etc -->
</select>
This would have to be repeated for each <select> in your <form>.
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.