Drop down live update in a form - php

How do you live update the content of drop down 2 based on the selection made in drop down 1 in a PHP based web form?
Would appreciate any code examples to work from.
Many thanks!

You are going to have to use AJAX, I would recommend jQuery's abstraction.
e.g.
<select id="sel1">
<option value="1">1</option>
<option value="2">2</option>
</select>
<select id="sel2">
</select>
<script type="text/javascript">
$('#sel1').change(funciton(){
$.ajax({url: 'fetchSel2.php',
data:{sel1:$('#sel1').val()},
success:function(data){
$('#sel2').html(data);
}
});
});
</script>
This presumes there is a 'fetchSel2.php' that is ready to serve the options for the second select.
e.g.
function getSecondOptions($sel1){
$r=mysql_query(RELEVANT_QUERY);
$opts='';
if($r && mysql_num_rows($r)>0){
while(list($label,$val)=mysql_fetch_row($r)){
$opts.='<option value="'.$val.'">'.$label.'</option>';
}
}
return $opts;
}
if(isset($_GET['sel1'])){
echo getSecondOptions($_GET['sel1']);
}
exit;

For live update, you need to use AJAX and require JS enabled browser. If the user-browser don't support JS or JS is disabled, the only option is to submit the form and reload the whole page with the updated option in the 2nd dropdown. If you want the JS code to perform AJAX, can you kindly tell me the JS library you want to use, so I can provide the code accordingly.

What you are looking for is a cascading dropdown list. This is done using AJAX triggered in sequence by each dropdown. Here is an example via Google (http://codestips.com/php-ajax-cascading-dropdown-using-mysql/), note I'm not endorsing this link, it's just the first reasonable result.

I recently did this with jQuery http://jsfiddle.net/tBrXt/1/

You have these options:
Use AJAX if you don't want the form to refresh and update parts of
the form.
If you don't want to use ajax and can bear with refreshing the whole
form, you can capture the onChange event of the drop down using
javascript.
If the user does not have javascript enabled, the above 2 methods
will fail. Therefore, it is best to include a button users can click,
which will ask the PHP side to rerender the form.
My personal preference is to use the last method as a fall back for those who do not have javascript enabled. Then use the first method (AJAX) to progressively enhance the form for those that have javascript.

Related

How do I get dropdowns in a PHP script to submit the form on change?

Ok... First off, I know this isn't a new question.
But, for some reason none of the suggestions Google has found for me (dating back to the begining of time even) are working. So, please bear with me.
Let's say, I have a script structured something like this:
<?php
try {
print "<table><form id='menu' action='index.php' method='POST'><tr>";
print "<td>Select A Fruit</td><td><select name=fruit>
<option value=''></option>
<option value='apple'>Apple</option>
<option value='orange'>Orange</option>
<option value='pear'>Pear</option></select></td></tr>";
print "<tr><td><input type='submit' name='submit' value='Submit'></td></tr></form></table>";
if (isset($_POST['submit'])){
if (!empty($_POST['fruit'])){
//Do whatever the form is supposed to trigger.
}
else {
//Nothing selected; handle however makes sense.
}
}
}
catch(Exception $e) {die( print_r( $e->getMessage() ) );}
?>
And instead of using the button, I want it to submit the form as soon as an option is selected.
Based on my searches, the textbook answer appears to be to modify the Select tag with an onchange attribute calling a JavaScript method like so:
<select name='fruit' onchange='document.getElementById('menu').submit()'>
or the short form:
<select name='fruit' onchange='this.form.submit()'>
But here is where I'm stuck...
None of the posts I found explain where you tell the browser/interpreter to drop out to JavaScript to make that work. So, this change does nothing for me.
What am I missing here?
I would get away from the dom level 0 handler and set the select's onchange handler to a function that grabs your form, and calls submit on it.
document.getElementById("yourSelectId").onchange = function() {
document.forms["formsId"].submit();
};
I'm showing you a more robust way of adding event handlers to dom elements. Instead of saying onchange="blah()" you can set up a body onload function that'll run when your dom is ready, then you can use JavaScript to add your handlers:
<body onload="init()">
function init() {
document.getElementById("yourSelectId").onchange = function() {
document.forms["formsId"].submit();
};
}
Or, you can skit the ugly <body onload="init()"> altogether and just put the code
document.getElementById("yourSelectId").onchange = function() {
document.forms["formsId"].submit();
};
in a regular script block at the bottom of your body
Your markup isn't valid, a table-element cannot have a form as child-element(wrap the form around the table)
Choose another name for the submit-button, otherwise you will receive an error in IE when calling submit()
I would suggest using an event listener rather than adding the attribute to your code. Also, it is recommended to have the static page display the submit button, and simply remove it via javascript after the page loads.
element.addEventListener Example
<script type="text/javascript">
document.getElementById("yourSelectId").addEventListener("change", function(){document.forms["yourFormId"].submit();});
</script>
To read more about element.addEventListener (esp. to see why it's important to use it), check out the article on element.addEventListener at MDN.
How javascript works in onchange attribute
But here is where I'm stuck... None of the posts I found explain where you tell the browser/interpreter to drop out to JavaScript to make that work. So, this change does nothing for me.
Attributes such as onchange, onclick, etc (notice "on" at the beginning) parse the value as javascript. Ergo, that is where you are telling the browser to use javascript to make it work :)

Populating Drop Down Boxes Via Javascript Change Selected Item

I populate a drop down box from an array that uses Javascript on the page load. But I am pulling data out of a database how would I change which one was selected? I would prefer not to have to use PHP to create the drop down boxes, as I have other non php things that use the javascript as well. What Can I do to get my Drop DownList populated from PHP?
You can see that it just calls the SelectdeptDropdown function.
<label for="collegedropdown">Collge</label>
<select name="collegedropdown" id="collegedropdown" onChange="SelectDeptDropdown();">
<option selected="selected">Choose a college</option>
</select>
<br />
<label for="deptdropdown">Department</label>
<select name="deptdropdown" id="deptdropdown">
<option selected="selected">Choose a department</option>
</select>
Javascript Code:
removeAllOptions(document.profilecreate.deptdropdown);
addOption(document.profilecreate.deptdropdown, "", "Choose One", "");
if(document.profilecreate.collegedropdown.value == 'MY CHOICE #1'){
//all options here
}
//repeat for other cases here
NOTE: removeAllOptions calls another function that simply clears the dropdown list. addOption calls a function that creates the option element.
basically you need to use an XHR Request. The XHR request will hit another end point of your php server which will return data for you to populate the dropwdown field and then you can use some smart javascript to insert into the dom.
Tne end point should ideally return a json data which will only be the dropdown values and you generate the markup on the client side this is ont compulsory but recommended.. read more abt XHR and json here.
Finally I would suggest you to use a library like jquery that gives you simple api for XHR requests and DOM manipulation using which you can get your job done quickly.

Clearing a selected item from a dropdown using PHP

I used the code below to remove a selected item from drop down, but when I remove one, the other item pops up. For example, if these are my options: "guns, cars, money", as I select and delete guns, cars and money remains. However, if I select cars and delete it, the deleted guns options pops up again. It is frustrating.
<?php
$opts = array("guns","knives","ammo");
$selected = array($_POST['selectMenu']);
$revisedOpts = array_diff($opts,$selected);
?>
<form method="post">
<select name='selectMenu'><?php
foreach($revisedOpts as $v) {
echo "<option>".$v."</option>";
}
?></select>
<input onclick="array_diff()" name="Collect" type="submit" value="submit" />
</form>
PHP only acts when the page is loaded, and you load the same code over and over. In order for previously deleted options to stay deleted, you need some kind of data persistence (like a database). Otherwise, you can use javascript to manipulate the select options on the client side browser. Here is a good discussion
If you must bind the action to onclick() and receive the event on the server side, then you will need to use an AJAX call. The onclick calls a separate PHP script which deletes the option and returns some kind of success message.
you want to have a look at some js code to do this. look at something like that http://www.mredkj.com/tutorials/tutorial_mixed2b.html
use jquery
jquery auto suggestion

How to handle event of selecting an item in <select> in html with jQuery?

<select id ="facetFilterList" class="ui-widget-content ui-corner-all" size="18" multiple="multiple">
So I want to trigger some event whenever the user clicks on an item and getting it's value as well.
$('#facetFilterList').change(function () { alert($(this).val()); })
The PHP part is not important here , we are working on the client side here.
basically u can use jquery $.get or $.post to post the value from the listbox when the user click on and and update something else back.
if you will be more specific with what you're trying to do, i bet other SO-ers will be able to help you better.
but for starters, you can play with this.

Problem with keeping selected value in form after reloading page

I'm trying to populate a second dropdown in a dynamic way based on a previs selected dropdown.
However, I've managed to write get the page to reload when I choose anything in the dropdownbox but the chosen value isnt passed after reloading.
I have register_globals turned off (and prefer to) and i'm using the GET function to submit the form. However when I try setting values in the URL I cant get it to work.
Example: dropdown.php?area=1 still gives me a value in the dropdownbox with the default value.
What am I doing wrong? Running on a LAMP server. Apache 2.2, php 5.3.
Note: I found the php code here on the web wwich is suppose to help me pass the GET variable and select the option in the selectbox.
This is my code:
<html>
<head>
<SCRIPT language=JavaScript>
function reload(form)
{
var val=form.area.options[form.area.options.selectedIndex].value;
self.location='dropdown.php?area=' + val ;
}
</script>
</head>
</body>
<? #$area=$HTTP_GET_VARS['area']; ?>
<form action="" method="get">
<select name="area" id="area" onchange="reload(this.form)">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
</form>
</body>
</html>
Also, if this could be done with POST (or equivalent function) it would be even better.
Regards.
I think you're not specifying anywhere which one of the options should be selected on page load. Depending on the value of $area, you should add something like
<option selected>1</option>
You could easily do this with a couple of lines of PHP when rendering the option nodes:
<? if $area == 1
print '<option selected>1</option>';
?>
etc.
Alternatively, you could just populate the second combo using client-side javascript eliminating the need for a page reload. If you need to do some sensitive server-side processing to calculate the value of the second combo, do it in a background AJAX call using jQuery (examples here). Postbacks for this kind of thing are kind of undesirable and old-fashioned these days.
Regarding the GET issue, if submitting the form has any side effects (eg. a change in state in the user's account, deleting something, creating a new entity) then it should definitely be a POST. Discussion here for example.

Categories