populate dropdown on selection of other dropdown - php

I have two drop-down boxes. I want to populate second drop-down box on selection in the first drop-down box. My values are retrieving from database. Is this possible without using php or I need intermediate ajax and php file to get values from first drop-down and populate values file. Or this is possible without using php I mean only using Jquery. Please give me hint to do that.
Suppose I have 2 countries. First is INDIA and second is USA. ON first drop-down I am selecting countries and if first dropdown is selected than second dropdown populate its respective states.

if you encode your data into JSON format, then you can do something like this:
for HTML:
<select name='country' id='country'>
<option value='india'>India</option>
<option value='usa'>USA</option>
</select>
<select name='dates' id='dates'>
</select>
jQuery:
data = {
india: ['2011-03-11','2010-02-01'],
usa: ['2006-03-11','2009-02-01']
}
$('#country').change(function(){
var dateopts = ''
$.each(data[$(this).val()],function(i,v){
dateopts += "<option value='"+v+"'>"+v+"</option>"
})
$('#dates').html(dateopts)
})
Which when the country is changed, will build and populate the options for the second select box.
See the working example here: http://jsfiddle.net/xHxcD/
The above method requires all data to be sent to client side with the initial page request. If you have lots of data, it would be better to receive the data via AJAX. It would be simplest to do this by building an object in PHP with the same data structure as your client side, then use json_encode to convert it into as JSON string and echo it out.
Reading this into your client side would then be as simple as this:
$.ajax('myJsonData.php?country=india',function(jsonData){ data.india = jsonData })

You could do it either way. If you dont want to use ajax, just load every single option into an object. Then when you select something from select #1, populate #2 with the assoicated array of data from your object.
If I were doing it, I wouldn't do it with ajax unless there was a TON of data.

Yes you can do it without using php. For that you've to assign two different states list in Javascript array and base on the selection just change the options in the other select box. As simple as that.
You can assign the javascript array using your serverside scripting language while loading the page if you're using database to store the states.
But do not do this unless you've very small amount data. In your case you've only 2 countries so you can go ahead with it.

Lets take an easy example, I'm using this for the same purpose that you want and it works perfectly fine.
This is the country dropdown:
<?php
$countrylist=mysql_query("SELECT * FROM country ORDER BY name ASC");
echo "<select name='country' id='country' onchange=\"reload(this.form)\" title='Country e:g; United Kingdom,Pakistan'><option value='0'>Select Country</option>";
while($clist=mysql_fetch_array($countrylist))
{
echo "<option value='$clist[Name]'>$clist[Name]</option>"."<br/>";
}
echo "</select>";
?>
This is the region dropdown:
<select name="region" id="region" ></select>
Now make a seperate file named crlist.js and include it in the page having above code like this:
<script type="text/javascript" src="crlist.js"> </script>
code for crlist.js:
var request = false;
/*#cc_on #*/
/*#if (#_jscript_version >= 5)
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
request = false;
}
}
#end #*/
function fillSelect(country,path) {
var url = path+"crlist.php?country=" + country;
request.open("GET", url, true);
request.onreadystatechange = go;
request.send(null);
}
function go() {
if (request.readyState == 4) {
//if (request.status == 200) {
var response = request.responseText;
var list=document.getElementById("region");
for (i = list.length - 1; i>=0; i--) {
list.remove(i);
}
var records=response.split('|');
for (i=1; i<records.length; i++) {
//alert("rcord="+records[i]);
var record=records[i].split('*');
var region=record[0];
//alert("region="+region);
var regionid=record[1];
//alert("regionid="+regionid);
var x=document.createElement('option');
//var y=document.createTextNode(region);
x.text=region;
//x.value=region;
//alert(x.text);
//x.appendChild(y);
//list.appendChild(x);
list.options.add(x);
}
//}
}
}
function initCs(path) {
if (!request && typeof XMLHttpRequest != 'undefined') {
request = new XMLHttpRequest();
}
var country=document.getElementById('country');
country.onchange=function() {
if(this.value!="Select") {
var list=document.getElementById("region");
for (i = list.length - 1; i>=0; i--) {
list.remove(i);
}
//while (list.childNodes[0]) {
//list.removeChild(list.childNodes[0]);
//}
}
fillSelect(this.value,path);
//alert(this.value);
}
//fillSelect(country.value);
}
Now make a seperate file named crlist.php.
Code for crlist.php:
<?php
require_once 'yourconfigfile.php';
$cname = $_GET['country'];
$query="select ID,Name from city where CountryCode=(select code from country where name='$cname') Order By Name ASC";
$res = mysql_query($query) or die(mysql_error());
while($region = mysql_fetch_array($res)){
echo "<option value='".$region['Name']."'>".$region['Name']."</option>";
}
?>
Now add following script on the page having dropdowns:
<script type="text/javascript" src="crlist.js"> </script>
<script>
$(document).ready(function() {
initCs("");
});
</script>
This is my own script, and i've assumed that you have created country and region tables. But you need to tweak the queries and above code according to your db structure.
Reference to my answer: Cascade Dropdown List using jQuery/PHP
Hope this helps.

Related

PHP Auto update selectbox based on 1st selectbox

I have 2 selectboxes
<h3>Results</h3>
<select id="register_form" name="sport" />
<option value="Rugby">Rugby</option>
<option value="Cricket">Cricket</option>
<option value="Football">Football</option>
</select>
<?php
echo'<select name="match">';
echo'<option value="'.$row['event_id'].'">'.$row['team1'].' VS '.$row['team2'].'</option>';
echo'</select>';
?>
<input id="register_form" type="submit" value="Display" name="submit" />
User searches for a result by:
selecting sport type in 1st selectbox and then in 2nd selectbox option values are populated based on sport type.
Is it possible to do this in PHP without the user having to first press submit to get the $_POST value of sport type?
What is my best option here?
PHP always need to reload the page to refresh your informations, so, as anant kumar singh said, you need to use AJAX for that. And as yak613 said, jQuery will help you to use AJAX easily
1.Ajax is the only option what you asked for that(without page refresh)
When you use php it's only possible with page refresh. but with ajax without page refresh it's possible.
helping links are:-
Use jQuery to change a second select list based on the first select list option
https://www.daniweb.com/web-development/php/threads/372228/php-and-ajax-auto-populate-select-box
https://remysharp.com/2007/01/20/auto-populating-select-boxes-using-jquery-ajax
You can use this Multiple Select Dropdawn lists: http://coursesweb.net/ajax/multiple-select-dropdown-list-ajax_t , it can be used for multiple sets of Select lists.
I've faced with the same problem in my project. But the needed functionality was higher - not two dependent selectboxes and bigger number. I've written a simple function to load my selectboxes:
//formId - form where selectbox is
//name - attribute "name" of selectbox
//dataSourceUrl - url to PHP-file
//affectingField - string with value that filters the selecbox's data
function loadSelectbox( formId, name, dataSourceUrl, affectingField ){
//console.log('Loading data to selectbox name="'+name+'":');
var selectbox = $('#'+formId+' select[name="'+name+'"]');
if(selectbox){
//console.log("Selecbox found");
if(affectingField != null){
var affectingValue = $('#'+formId+' [name="'+affectingField+'"]').val();
dataSourceUrl += '?affectingValue='+affectingValue;
}
var options = selectbox.find('option');
var jqxhr = $.ajax({
url: dataSourceUrl,
dataType: 'text'
})
.done(function(data) {
//console.log(data);
if(data != ""){
var optionsObject = JSON.parse(data);
var i = 0;
console.log(optionsObject);
var options = [];
$(optionsObject).each(
function(){
options[i] = '<option value="'+$(this)[0]['val']+'">'+$(this)[0]['text']+'</option>';
i++;
}
);
selectbox.html(options);
if(urlParamsSet[name] == false){
setParamFromUrl(name);
}
}
else{
selectbox.html('<option value="">Все</option>');
}
})
.fail(function() {
alert("Problems with server answer");
})
selectbox.prop("disabled", false);
}
else{
console.log("No selectbox with such name");
}
}
Not saying that this code is perfect, but it works. PHP-file must return the values to selecbox in JSON format (convert from with structure: array(index, value, text) ).

Load an html table from a mysql database when an onChange event is triggered from a select tag

So, here's the deal. I have an html table that I want to populate. Specificaly the first row is the one that is filled with elements from a mysql database. To be exact, the table is a questionnaire about mobile phones. The first row is the header where the cellphone names are loaded from the database. There is also a select tag that has company names as options in it. I need to trigger an onChange event on the select tag to reload the page and refill the first row with the new names of mobiles from the company that is currently selected in the dropdown list. This is what my select almost looks like:
<select name="select" class="companies" onChange="reloadPageWithNewElements()">
<?php
$sql = "SELECT cname FROM companies;";
$rs = mysql_query($sql);
while($row = mysql_fetch_array($rs)) {
echo "<option value=\"".$row['cname']."\">".$row['cname']."</option>\n ";
}
?>
</select>
So... is there a way to refresh this page with onChange and pass the selected value to the same page again and assign it in a new php variable so i can do the query i need to fill my table?
<?php
//$mobileCompanies = $_GET["selectedValue"];
$sql = "SELECT mname FROM ".$mobileCompanies.";";
$rs = mysql_query($sql);
while ($row = mysql_fetch_array($rs)) {
echo "<td><div class=\"q1\">".$row['mname']."</div></td>";
}
?>
something like this. (The reloadPageWithNewElements() and selectedValue are just an idea for now)
Save the value in a hidden input :
<input type='hidden' value='<?php echo $row['cname'] ?>' id='someId' />
in your JavaScript function use the value from this hidden input field:
function reloadPageWithNewElements() {
var selectedValue = document.getElementById('someId').value;
// refresh page and send value as param
window.location.href = window.location + '?someVal='+ selectedValue;
}
Now again in your PHP file retrieve this value from url for use as:
$someVal = null;
if (isset($_GET['someVal']) {
$someVal = $_GET['someVal'];
}
see if this works!!!
The best option would be using AJAX.
reloadPageWithNewElements() is a function which calls a page of your own site which will return the data you would like to put in your table.
If you are using JQuery, AJAX is very easy to implement:
$.ajax({
url: '/yourPage',
data: { selectedCompany: $('.companies').val() },
success: function(result) {
//delete your tablerows
$(".classOfTable tr").remove();
//put the result in your html table e.g.
$('.classOfTable').append(result);
},
dataType: html
});
The browser will send a request to "/yourPage?selectedCompany=Google" or something
All you have to do is let this page print out only html (maybe even easier is to print only the tablerow (<tr>).
If you have any further questions, please ask.
I would use jQuery to do it.
first You need to add 'id' attribute to every option tag
<option id="option1">
<option id="option2">
and so on...
then with jQuery:
$('<option>').change(function() {
var id=$(this).attr('id');
...save data here (i.e: with ajax $.post(url, { selected_id: id}, callback }
});

Getting a record row in php using javascript

Coming from Adobe Flex I am used to having data available in an ArrayCollection and when I want to display the selected item's data I can use something like sourcedata.getItemAt(x) which gives me all the returned data from that index.
Now working in php and javascript I am looking for when a user clicks a row of data (in a table with onClick on the row, to get able to look in my data variable $results, and then populate a text input with the values from that row. My problem is I have no idea how to use javascript to look into the variable that contains all my data and just pull out one row based on either an index or a matching variable (primary key for instance).
Anyone know how to do this. Prefer not firing off a 'read' query to have to bang against the mySQL server again when I can deliver the data in the original pull.
Thanks!
I'd make a large AJAX/JSON request and modify the given data by JavaScript.
The code below is an example of an actual request. The JS is using jQuery, for easier management of JSON results. The container object may be extended with some methods for entering the result object into the table and so forth.
PHP:
$result = array();
$r = mysql_query("SELECT * FROM table WHERE quantifier = 'this_section'");
while($row = mysql_fetch_assoc($r))
$result[$row['id']] = $row;
echo json_encode($result);
JavaScript + jQuery:
container.result = {};
container.doStuff = function () {
// do something with the this.result
console.debug(this.result[0]);
}
// asynchronus request
$.ajax({
url: url,
dataType: 'json',
data: data,
success: function(result){
container.result = result;
}
});
This is a good question! AJAXy stuff is so simple in concept but when you're working with vanilla code there are so many holes that seem impossible to fill.
The first thing you need to do is identify each row in the table in your HTML. Here's a simple way to do it:
<tr class="tablerow" id="row-<?= $row->id ">
<td><input type="text" class="rowinput" /></td>
</tr>
I also gave the row a non-unique class of tablerow. Now to give them some actions! I'm using jQuery here, which will do all of the heavy lifting for us.
<script type="text/javascript">
$(function(){
$('.tablerow').click(function(){
var row_id = $(this).attr('id').replace('row-','');
$.getJSON('script.php', {id: row_id}, function(rs){
if (rs.id && rs.data) {
$('#row-' + rs.id).find('.rowinput').val(rs.data);
}
});
});
});
</script>
Then in script.php you'll want to do something like this:
$id = (int) $_GET['id'];
$rs = mysql_query("SELECT data FROM table WHERE id = '$id' LIMIT 1");
if ($rs && mysql_num_rows($rs)) {
print json_encode(mysql_fetch_array($rs, MYSQL_ASSOC));
}
Maybe you can give each row a radio button. You can use JavaScript to trigger an action on selections in the radio button group. Later, when everything is working, you can hide the actual radio button using CSS and make the entire row a label which means that a click on the row will effectively click the radio button. This way, it will also be accessible, since there is an action input element, you are just hiding it.
I'd simply store the DB field name in the td element (well... a slightly different field name as there's no reason to expose production DB field names to anyone to cares to view the page source) and then extract it with using the dataset properties.
Alternatively, you could just set a class attribute instead.
Your PHP would look something like:
<tr>
<td data-name="<?=echo "FavoriteColor"?>"></td>
</tr>
or
<tr>
<td class="<?=echo "FavoriteColor"?>"></td>
</tr>
The javascript would look a little like:
var Test;
if (!Test) {
Test = {
};
}
(function () {
Test.trClick = function (e) {
var tdCollection,
i,
field = 'FavoriteColor',
div = document.createElement('div');
tdCollection = this.getElementsByTagName('td');
div.innerText = function () {
var data;
for (i = 0; i < tdCollection.length; i += 1) {
if (tdCollection[i].dataset['name'] === field) { // or tdCollection[i].className.indexOf(field) > -1
data = tdCollection[i].innerText;
return data;
}
}
}();
document.body.appendChild(div);
};
Test.addClicker = function () {
var table = document.getElementById('myQueryRenderedAsTable'),
i;
for (i = 0; i < table.tBodies[0].children.length; i += 1) {
table.tBodies[0].children[i].onclick = Test.trClick;
}
};
Test.addClicker();
}());
Working fiddle with dataset: http://jsfiddle.net/R5eVa/1/
Working fiddle with class: http://jsfiddle.net/R5eVa/2/

Populating drop down boxes in php

just a quick one im looking to populate three drop down boxes to filter data and each one of them is going to affect the next.
what i want is for
Drop down 1 has company
once drop down 1 is selected the second drop down is populated with the branches for that company
once selected the third drop down is populated by the staff members for that company in that branch then when i press search it should pull the data for that 1 staff member. all of the information is in one table
the table i have is called "stafflist"
the columns are "company", "branch" and "staffname" each staff member has an autonumber id field which i use as a lookup called "staffID"
Thank you for any help
Regards
Slowie
Lets take an easy example, This is a javascript solution. I'm using this and it works perfectly fine. This script work in case if you select a country it populates its corresponding cities in the second dropdown. You can take some idea and use this for your case where you can deal with three dropdowns respectively.
This is the country dropdown:
<?php
$countrylist=mysql_query("SELECT * FROM country ORDER BY name ASC");
echo "<select name='country' id='country' onchange=\"reload(this.form)\" title='Country e:g; United Kingdom,Pakistan'><option value='0'>Select Country</option>";
while($clist=mysql_fetch_array($countrylist))
{
echo "<option value='$clist[Name]'>$clist[Name]</option>"."<br/>";
}
echo "</select>";
?>
This is the region dropdown:
<select name="region" id="region" ></select>
Now make a seperate file named crlist.js and include it in the page having above code like this:
<script type="text/javascript" src="crlist.js"> </script>
code for crlist.js:
var request = false;
/*#cc_on #*/
/*#if (#_jscript_version >= 5)
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
request = false;
}
}
#end #*/
function fillSelect(country,path) {
var url = path+"crlist.php?country=" + country;
request.open("GET", url, true);
request.onreadystatechange = go;
request.send(null);
}
function go() {
if (request.readyState == 4) {
//if (request.status == 200) {
var response = request.responseText;
var list=document.getElementById("region");
for (i = list.length - 1; i>=0; i--) {
list.remove(i);
}
var records=response.split('|');
for (i=1; i<records.length; i++) {
//alert("rcord="+records[i]);
var record=records[i].split('*');
var region=record[0];
//alert("region="+region);
var regionid=record[1];
//alert("regionid="+regionid);
var x=document.createElement('option');
//var y=document.createTextNode(region);
x.text=region;
//x.value=region;
//alert(x.text);
//x.appendChild(y);
//list.appendChild(x);
list.options.add(x);
}
//}
}
}
function initCs(path) {
if (!request && typeof XMLHttpRequest != 'undefined') {
request = new XMLHttpRequest();
}
var country=document.getElementById('country');
country.onchange=function() {
if(this.value!="Select") {
var list=document.getElementById("region");
for (i = list.length - 1; i>=0; i--) {
list.remove(i);
}
//while (list.childNodes[0]) {
//list.removeChild(list.childNodes[0]);
//}
}
fillSelect(this.value,path);
//alert(this.value);
}
//fillSelect(country.value);
}
Now make a seperate file named crlist.php.
Code for crlist.php:
<?php
require_once 'yourconfigfile.php';
$cname = $_GET['country'];
$query="select ID,Name from city where CountryCode=(select code from country where name='$cname') Order By Name ASC";
$res = mysql_query($query) or die(mysql_error());
while($region = mysql_fetch_array($res)){
echo "<option value='".$region['Name']."'>".$region['Name']."</option>";
}
?>
Now add following script on the page having dropdowns:
<script type="text/javascript" src="crlist.js"> </script>
<script>
$(document).ready(function() {
initCs("");
});
</script>
This is my own script, and i've assumed that you have created country and region tables. But you need to tweak the queries and above code according to your db structure. In your case you have to create tables for company, branches and employees.
Hope this helps.
Have you ever heard about AJAX() OR jQuery ? if not then refer those link first; actually for your task you need to use Ajax OR jquery based dropdown boxes. which can make your dream success. :)
refer below link for your solution.
If any help needed you can feel free to ask me..
EDIT As per your commnet :
Step-1:- "SELECT company_id,company_name from company_table WHERE $condition ";
Step-2:- Fill first drop down box with record of first query set.
Step-3:- call jquery.ajax function onchange event of first drop down box in which call one
php page i.e: getRecords.php.
Step-4:- In getRecords.php page you need to get all the Branches of that company by passing company id in ajax and return a record array as response.
Step-5:- Fill second drop down with these records and again onchange event call another jquery.ajax request for final drop down box and do all things same as Step-4.
I think its all steps what you need for. still have any issue let me inform.
Thanks.

What's the best and easiest way to Populate a dropdown based on another dropdown

Very simply, I have one dropdown menu dynamically populated with data:
SQL Code
$querycourse = "SELECT course, COUNT(course) AS count FROM acme WHERE course IS NOT NULL GROUP BY course ";
$procc = mysqli_prepare($link, $querycourse);
$queryc = mysqli_query($link, $querycourse) or die(mysqli_error($link));
PHP Code
echo "<select name='course[]' value='' multiple='multiple' size=10>";
// printing the list box select command
echo "<option value=''>All</option>";
while($ntc=mysqli_fetch_array($queryc)){//Array or records stored in $nt
echo "<option value=\"$ntc[course]\">\"$ntc[course]\"</option>";
/* Option values are added by looping through the array */
}
echo "</select>";// Closing of list box
What I need is another dropdown that is populated with data based on a selection from the first dropdown box.
I am using MySQL, PHP, Javascript and can also (at a push) use jQuery. I have no experience in Ajax.
Would anyone be kind enough to point me in the right direction?!
Thanks in advance, as always,
Homer.
First and Best Method (If you have or may have enough option specific data)
Use AJAX. It is the easiest way, I think, compared to the other ways to implement the same. Use Jquery to implement AJAX. It makes AJAX a piece of cake! Here I share my piece of cake for you -
Following is roughly the complete code you need -
Call a javascript function populateSecondDropdown() on your first select like this -
echo "<select name='course[]' value='' multiple='multiple' size=10 onchange='populateSecondDropdown(this, 'http://yourprojectUrl','Any Subject');'>";
// printing the list box select command
echo "<option value=''>All</option>";
while($ntc=mysqli_fetch_array($queryc))
{//Array or records stored in $nt
echo "<option value=\"$ntc[course]\">\"$ntc[course]\"</option>";
/* Option values are added by looping through the array */
}
echo "</select>";// Closing of list box
Define an ajax call inside inside the populateSecondDropdown() function -
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript">
function populateSecondDropdown(object,baseUrl)
{
$.ajax({
type: "POST",
url: baseUrl+"/ajax/fetchOptions.php",
data: { id_option: $(object).val(), operation: 'get_subjects' },
dataType: "json",
success: function(data)
{
//Clear options corresponding to earlier option of first dropdown
$('select#secondDropdown').empty();
$('select#secondDropdown').append('<option value="0">Select Option</option>');
//Populate options of the second dropdown
$.each( data.subjects, function()
{
$('select#secondDropdown').append('<option value="'+$(this).attr('option_id')+'">'+$(this).attr('option_name')+'</option>');
});
$('select#secondDropdown').focus();
},
beforeSend: function()
{
$('select#secondDropdown').empty();
$('select#secondDropdown').append('<option value="0">Loading...</option>');
},
error: function()
{
$('select#secondDropdown').attr('disabled', true);
$('select#secondDropdown').empty();
$('select#secondDropdown').append('<option value="0">No Options</option>');
}
});
}
</script>
And finally the query to fetch 2nd dropdown's options in the AJAX processor file fetchOptions.php. You can use $_POST['id_option'] here to fetch the options under it. The database query here should fetch the option_id and option_name fields for every option (as expected by the jquery code inside $.each) and return a json encoded array like this:-
return json_encode(array("subjects" => $resultOfQuery));
Second Method (Using only javascript)
Fetch all the data for the second dropdown grouped by the field of the first dropdown. E.g. let's take courses displayed in the first dropdown and subjects under courses displayed in the 2nd
Create all the options of the 2nd dropdown. Assign classes equal to the courses while creating the options like this:-
$querycourse = "SELECT course, subject FROM subjects WHERE subject IS NOT NULL GROUP BY course ";
$procc = mysqli_prepare($link, $querycourse);
$queryc = mysqli_query($link, $querycourse) or die(mysqli_error($link));
echo "<select name='subjects[]' value='' multiple='multiple' size=100>";
echo "<option value=''>All</option>";
while($ntc=mysqli_fetch_array($queryc))
{//Array or records stored in $nt
echo "<option value=\"$ntc[subject]\" class=\"$ntc[course]\">\"$ntc[subject]\"</option>";
}
echo "</select>";
Then define onchange="displaySubjectsUnderThisCourse(this);" for the first dropdown and write this javascript :-
function displaySubjectsUnderThisCourse(object)
{
var selectedCourse = $(object).val();
//Display the options with class = the selected option from first dropdown
$("."+selectedCourse).removeClass("hidden"); //define a class hidden with display:none;
$('option:not(.selectedCourse)').hide(); // hide all options whose class is other than selectedCourse - Not sure whether this will work or not, though
//Deselect any previous selections
//If single option selection is allowed
$('select#secondDropdown option').attr('selected', false);
// or following if multiple selection is allowed (needed for IE)
$('select#secondDropdown option').attr('selectedIndex', -1);
}
The basic idea here is to hide/display option groups but my code may have errors.
Finally, please note, the second method (fetching all the option values) would be better only if you have limited small amount of data and are very sure there will always be less data in future. But, since nobody can be so certain about the future, it is advisable to use the AJAX method always.
There are two methods:
First, you can load all choices for
the second select list into a
JavaScript array. When an option is
selected in the first select,
populate the second with the
appropriate options.
Second, you can use Ajax to make a
call to the server and fetch the
options for the second select based
on the choice of the first. The
server would then return a list of
options (one per line, tab delimited
is how I do it) that you parse and
use to populate the second select.
The first option is very fast and easy, but may take a while to load if you have a large list of options for the second select.
The second option is more complicated, but much more flexible.
Here's some Ajax code to get you started:
Create a request:
var HTTP_UNINITIALIZED = 0;
var HTTP_SETUP_NOTSENT = 1;
var HTTP_PROCESSING = 2;
var HTTP_PARTIAL_RESULT = 3;
var HTTP_COMPLETE = 4;
function createRequest()
{
var request = null;
try
{
request = new XMLHttpRequest();
}
catch( failed_once )
{
try
{
request = new ActiveXObject( "Msxml2.XMLHTTP" );
}
catch( failed_twice )
{
try
{
request = new ActiveXObject( "Microsoft.XMLHTTP" );
}
catch( failed_thrice )
{
request = null;
}
}
}
return( request );
}
Send the request:
var request = createRequest();
function doSearch( value )
{
getURL = "<url to get list>?Value=" + value;
request.open( "POST", getURL, true );
request.onreadystatechange = showResults;
request.send( null );
}
Use the results:
function showResults()
{
if( request.readyState == HTTP_COMPLETE && request.status == 200 )
{
if( request.responseText != "" )
{
var lines = request.responseText.split( "\n" );
for( i = 0 ; i < lines.length ; i++ )
{
var parts = lines[i].split( "\t" );
// populate the second select
}
}
}
}
How you handle the server side portion is up to you.

Categories