jQuery UI chained select-menu. Form resets when button is clicked - php

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>.

Related

Presetting a select element

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.

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

Displaying Select on GET

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>

2 drop down menus w/o submit button

I would like to know how to submit two drop down menus w/o a submit button. I want to populate the second drop down menu on selection of the first and then be able to echo out the selection of the second drop down menu. Data for the second drop down menu is obtained from a mySQL database. I am using two forms on my page, one for each drop down menu.
<form method="post" id="typeForm" name="typeForm" action="">
<select name="filterType" onchange="document.getElementById('typeForm').submit()">
<option <?php if ($_POST['filterType'] == 'none') print 'selected '; ?> value="none">Filter by...</option>
<option <?php if ($_POST['filterType'] == 'employee') print 'selected '; ?> value="employee">Employee</option>
<option <?php if ($_POST['filterType'] == 'taskName') print 'selected '; ?> value="taskName">Task</option>
</select>
<noscript><input type="submit" value="Submit"/></noscript>
</form>
<form method="post" id="categoryForm" name="typeForm" action="">
<select name="filterCategory" onchange="document.getElementById('categoryForm').submit()">
<option <?php if ($_POST['filterCategory'] == 'none') print 'selected '; ?> value="none"></option>
<?
$count2 = 0;
echo $rowsAffected2;
while ($count2<$rowsAffected2) {
echo "<option value='$filterName[$count2]'>$filterName[$count2]</option>";
$count2 = $count2 + 1;
}
?>
</select>
<noscript><input type="submit" value="Submit"/></noscript>
</form>
I can submit the first form with no problem. It retrieves values into the second drop down menu successfully.But on selecting a value from the second menu the page refreshes and I'm left with an two unselected drop down menus. I tried echoing the $_POST['filterCategory'] and didn't get a result. I tried using onchange="this.form.submit();" in both forms and I still get the same result. Is there a way to do this without using AJAX, JQuery or any complex Javascript script? I require to this completely in PHP.
I want to avoid the second refresh but still be able to gather the $_POST[''] data from the second selection.
use the same form for both selects
You have two ways of doing that.
You can either submit the form using AJAX; that will prevent the whole page from refreshing, and hence, losing the data in both select elements; that is also the coolest way to have it done.
OR
Using a single form, when both the first and second select elements are submitted, use their values to re-create the select elements.
The cleaner way to do it is still the first option; at least, that's what I'll use if I have to do it.

php form validation using session variable

I have a sign-up form in php, which sends data to another php form for insertion into mysql
If any of the fields are missing, an error mesage is sent back to sign-up form using session variable (value="<?php echo $_SESSION['error']; ?>") along with all the fields the user had already filled up ( so that they dont have to fill it up again ) using session variables as well..
for text boxes im using value="<?php echo $_SESSION['fname']; ?>" which works fine.. but this doesnt seem to work for drop down boxes or radio buttons..
any suggestions?
Drop down boxes and radio buttons use a selected or click index. You need to check for each one if it was selected or clicked and give it the appropriate attribute.
<?php if($_SESSION['dropBox1'] == "value") echo ' selected="selected"'; ?>
First, you shouldn't submit the form to another page for validation. Do it in the current page. And drop down lists and radio buttons value attribute is the value that is tied to the selection. Not what is displayed or in any way tells it that it is the selected item. #James beat me for code on how to show which is selected.
<select>
<option value="0" <?php echo $_SESSION['dropBox1'] == "0" ? ' selected="selected"' : '' ?>>option1</option>
<option value="1" <?php echo $_SESSION['dropBox1'] == "1" ? ' selected="selected"' : '' ?>>option2</option>
<option>etc..</option>
</select>

Categories