Hi
I'm now trying to have a dependent lists in a form
my form is a query based form
i.e. I fill my MySQL query from this form
I have around 30 fields/columns
each have number of values... sometimes 2 , sometimes 20.. maybe more !
I've searched the web to find a javascript code that helps me to do the dependent lists
I found few funtions.. but their work depends on INDEX !
they're very powerful functions.. i liked them.. but didn't know how to modify them until i get what i'm looking for
This is what I've found ( in two diff websites) - it's working if you copied it and pasted then tried it ! -
<html>
-
<head>
-
<script type="text/javascript">
-
function DepSelectOne(masterSelect){
-
var frm = masterSelect.form;
-
this.selectedBlock = 0;
-
this.selBoxes = new Array(masterSelect);
-
if((frm)&&(typeof Option != 'undefined')){
-
for(var c = 1;c < arguments.length;c++){
-
var selObj = frm[arguments[c]];
-
if((selObj)&&(selObj.type.indexOf('select') == 0)&&(selObj.type.indexOf('mult') < 0)&&(selObj.options.length > 2)){
-
this.selBoxes[this.selBoxes.length] = frm[arguments[c]];
-
}
-
}
-
if((this.selBoxes.length >1)&&(this.selBoxes.length == arguments.length)){
-
this.selectElement = this.selBoxes[0];
-
DepSelectOne.inst[this.index = this.selectElement.name] = this; //keep global record of this object instance.
-
this.selBoxes[0] = this;
-
this.optionBlock = new OptionBlock(0, this.selectElement, this.selectElement.options[0].value, this, 0);
-
this.next = new DepSelectOneNext(this.selBoxes, 1);
-
this.next.setSelection(this.optionBlock.getSelection());
-
this.selectElement.onchange = new Function('DepSelectOne.inst[\''+this.index+'\'].handleChange(0)');
-
}else{
-
//alert('DepSelectOne constructor could not find\nsufficient properly configured SELECT elements\nto initialise.');
-
}
-
}
-
}
-
DepSelectOne.inst = {}; //Globally accessible object to hold instances of the DepSelectOne Class.
-
//call chain terminating functions.
-
DepSelectOne.prototype.validateNext = DepSelectOne.prototype.reset = DepSelectOne.prototype.setSelection = DepSelectOne.prototype.setSelectedFromChild = function(){return true;}
-
DepSelectOne.prototype.validate = function(){
-
return ((this.optionBlock.lastSelection < 0)?false:this.next.validateNext());
-
}
-
DepSelectOne.prototype.init = function(selectedBlock){
-
if(selectedBlock >= 0){
-
this.optionBlock.lastSelection = selectedBlock;
-
}
-
if(this.optionBlock.lastSelection >= 0){
-
this.optionBlock.doElement();
-
if(window.setTimeout)setTimeout('DepSelectOne.inst[\''+this.index+'\'].refresh();', 5); //fix for Opera 7 timing problem. Harmless otherwise.
-
}
-
}
-
DepSelectOne.prototype.handleChange = function(ind){
-
this.selBoxes[ind].changed();
-
if(window.setTimeout)setTimeout('DepSelectOne.inst[\''+this.index+'\'].refresh();', 5); //fix for Opera 7 timing problem. Harmless otherwise.
-
}
-
DepSelectOne.prototype.refresh = function(){
-
this.selectElement.selectedIndex = this.optionBlock.lastSelection;
-
this.next.reset();
-
}
-
DepSelectOne.prototype.changed = function(){
-
this.optionBlock.readState();
-
this.next.setSelection(this.optionBlock.getSelection());
-
}
-
-
function DepSelectOneNext(selBoxes, selBoxIndex){
-
this.selectedBlock = -1;
-
this.classObj = selBoxes[0];
-
this.previous = selBoxes[(selBoxIndex-1)]
-
this.selectElement = selBoxes[selBoxIndex];
-
selBoxes[selBoxIndex] = this;
-
this.selectElement.onchange = new Function('DepSelectOne.inst[\''+this.classObj.index+'\'].handleChange('+selBoxIndex+')');
-
this.seperatorOption = new DepOption(this.selectElement.options[0]);
-
this.optionBlocks = [];
-
var startIndex = 1;
-
while(startIndex < this.selectElement.options.length){
-
var nextIndex = this.optionBlocks.length;
-
this.optionBlocks[nextIndex] = new OptionBlock(startIndex, this.selectElement, this.selectElement.options[0].value, this, nextIndex);
-
startIndex += this.optionBlocks[nextIndex].getOptionsTotal();
-
}
-
for(var cnt = 0,c = 0;c < this.optionBlocks.length;c++){
-
this.optionBlocks[c].blockStart = cnt;
-
cnt += this.optionBlocks[c].getItems();
-
}
-
if(++selBoxIndex < selBoxes.length){
-
this.next = new DepSelectOneNext(selBoxes, selBoxIndex);
-
}else{
-
this.next = this.classObj;
-
this.previous.init(this.selectedBlock);
-
}
-
}
-
DepSelectOneNext.prototype.reset = function(){
-
if((this.selectedBlock >= 0)&&(this.optionBlocks[this.selectedBlock].lastSelection >= 0)){
-
this.selectElement.selectedIndex = this.optionBlocks[this.selectedBlock].lastSelection;
-
this.next.reset();
-
}
-
}
-
DepSelectOneNext.prototype.setSelection = function(selBlock){
-
this.selectedBlock = selBlock;
-
if(this.selectedBlock < 0){
-
var opt = this.selectElement.options;
-
opt.length = 0; //clear options
-
opt[0] = this.seperatorOption.getOption();
-
this.selectElement.selectedIndex = 0;
-
this.next.setSelection(-1);
-
}else{
-
var blk = this.optionBlocks[this.selectedBlock];
-
blk.doElement();
-
this.next.setSelection(blk.getSelection());
-
}
-
}
-
DepSelectOneNext.prototype.changed = function(){
-
if(this.selectedBlock >= 0){
-
var blk = this.optionBlocks[this.selectedBlock];
-
blk.readState();
-
this.next.setSelection(blk.getSelection());
-
}
-
}
-
DepSelectOneNext.prototype.setSelectedFromChild = function(blockIndex){
-
if(this.selectedBlock < 0){ //only set from OptonBlock on the first attempt.
-
this.selectedBlock = blockIndex;
-
}
-
}
-
DepSelectOneNext.prototype.init = function(selBlock){
-
if(selBlock >= 0){
-
var blockIndex = 0;
-
while(!this.optionBlocks[blockIndex++].nextBlockTest(selBlock));
-
}
-
this.previous.init(this.selectedBlock);
-
}
-
DepSelectOneNext.prototype.validateNext = function(){
-
return (((this.selectedBlock < 0)||(this.optionBlocks[this.selectedBlock].lastSelection < 0))?false:this.next.validateNext());
-
}
-
-
function DepOption(optEl){
-
this.value = optEl.value;
-
this.text = optEl.text;
-
}
-
DepOption.prototype.getOption = function(){
-
return new Option(this.text, this.value);
-
}
-
-
function OptionBlock(startIndex, selectElement, seperatorValue, owner, blockIndex){
-
this.blockStart = 0;
-
this.owner = owner;
-
this.index = blockIndex;
-
this.selectElement = selectElement;
-
this.seperators = [];
-
this.optionBlock = [];
-
this.lastSelection = -1;
-
var opts = this.selectElement.options;
-
while((startIndex < opts.length)&&(opts[startIndex].value == seperatorValue)){
-
this.seperators[this.seperators.length] = new DepOption(opts[startIndex++]);
-
}
-
while((startIndex < opts.length)&&(opts[startIndex].value != seperatorValue)){
-
if((this.lastSelection < 0)&&(opts[startIndex].selected == true)){
-
this.lastSelection = this.optionBlock.length; //record first item selected, if any.
-
}
-
this.optionBlock[this.optionBlock.length] = new DepOption(opts[startIndex++]);
-
}
-
if(this.lastSelection >= 0)this.owner.setSelectedFromChild(this.index)
-
}
-
OptionBlock.prototype.getOptionsTotal = function(){
-
return (this.seperators.length + this.optionBlock.length);
-
}
-
OptionBlock.prototype.getItems = function(){
-
return this.optionBlock.length;
-
}
-
OptionBlock.prototype.nextBlockTest = function(selBlock){
-
if((selBlock >= this.blockStart)&&(selBlock < this.blockStart+this.optionBlock.length)){
-
this.lastSelection = selBlock - this.blockStart;
-
this.owner.selectedBlock = this.index;
-
return true;
-
}
-
return false;
-
}
-
OptionBlock.prototype.getSelection = function(){
-
return ((this.lastSelection < 0)?-1:(this.blockStart+this.lastSelection));
-
}
-
OptionBlock.prototype.doElement = function(){
-
var opt = this.selectElement.options;
-
opt.length = 0; //clear options
-
if((this.lastSelection < 0)&&(this.seperators.length > 0)){
-
opt[opt.length] = this.seperators[(this.seperators.length-1)].getOption();
-
}
-
for(var c = 0;c < this.optionBlock.length;c++){
-
opt[opt.length] = this.optionBlock[c].getOption();
-
}
-
this.selectElement.selectedIndex = ((this.lastSelection < 0)?0:this.lastSelection);
-
}
-
OptionBlock.prototype.readState = function(){
-
if(this.lastSelection < 0){
-
this.lastSelection = (this.selectElement.selectedIndex - 1);
-
this.doElement();
-
}else{
-
this.lastSelection = this.selectElement.selectedIndex;
-
}
-
}
-
</script>
-
</head>
-
<body onload="new DepSelectOne(document.forms['StateCityForm'].elements['State'], 'City');">
-
-
<form name="StateCityForm" ACTION="" METHOD="GET" TARGET="_blank">
-
-
First Choose State:
-
<select name="State">
-
<option value="choose">choose one</option>
-
<option value="State_1">State 1</option>
-
<option value="State_2">State 2</option>
-
<option value="State_3">State 3</option>
-
</select><br><br>
-
-
Now Select City:
-
<select name="City">
-
<option value="choose"><select previous first</option>
-
<option value="choose">select City for State_1</option>
-
<option value="City_A__State_1" >City A of State 1</option>
-
<option value="City_B__State_1" >City B of State 1</option>
-
<option value="City_C__State_1" >City C of State 1</option>
-
<option value="City_D__State_1" >City D of State 1</option>
-
<option value="City_E__State_1" >City E of State 1</option>
-
<option value="City_F__State_1" >City F of State 1</option>
-
-
<option value="choose">select City for State_2</option>
-
<option value="City_A__State_2" >City A of State 2</option>
-
<option value="City_B__State_2" >City B of State 2</option>
-
-
<option value="choose">select City for State_3</option>
-
<option value="City_A__State_3" >City A of State 3</option>
-
<option value="City_B__State_3" >City B of State 3</option>
-
<option value="City_C__State_3" >City C of State 3</option>
-
<option value="City_D__State_3" >City D of State 3</option>
-
</select>
-
-
</form>
-
-
</body>
-
</html>
-
this above code - is done with index.. i can't list all of mysql table values !!
let me tell you what i would like to do:
in the options of first list their should be this code:
this code will show fields available in the mysql table
[php]
<?
$sql = "SHOW FIELDS FROM myTable";
$result = mysql_query($sql);
while($row = mysql_fetch_row($result))
{?>
<option value="<?echo $row[0]?>"><?echo $row[0]?></option>
<?}
?>
[/php]
NOW .. to show values of ONE field (second list)
i use this code:
[php]
<?
$sql = "Select filed2 FROM myTable GROUP BY filed2";
$result = mysql_query($sql);
while($row = mysql_fetch_row($result))
{?>
<option value="<?echo $row[0]?>"><?echo $row[0]?></option>
<?}
?>
[/php]
In the above code, what i want is to have field2 be different depending on what user has selected in the first list
is there something like !! .. if user select item in the first list - take this item and assign it to field ?? ( so I'll use in my above code $field instead of field2 ) !!!
please help me.. I feel i'm almost there finding the right solution for this problem.. but need some help from you guys :)
P.S.1. I don't want to submit twice in the form i.e. i don't wonna sumbit first list so second list should be assigned.. i've tried that and made some other problems in my form
P.S.2. I don't want to use AJAX - .. what i need is php/html/javascript
Thanks in advance :)
48 2315
You are hacking somebody elses code to produce a solution in one go.
Fine if you know what you are doing.
Break this project into simple steps and solve each problem in turn.
You surely don't expect us to wade through this lot and make it work like you are expecting?
well, I found this code in two places.. and they said there to readers to look at the webpage source - i.e. they gave the permission to do that
I posted the code here so you guys can understand easily what I'm talking about
this is not many problems together - it's only one problem called (controlled/dependent 2 lists) where what's selected in one list should be used in mysql query in the second list to get the values of the first list selection
Heya, coool.
So the idea is to have two select elements, and when you select anything from the first select, the second select gets populated depending on what you picked. Does that sound right?
yes that's exactly what I'm looking for..
similar to countries and cities -- if someone selects a country - then in the second list cities of that country should be shown only
in both select statements i should populate the options in a query similar to the last two portion of codes in my first post
but i don't want to submit twice in the form - and i don't want to use AJAX -- is there any other solution !! --- maybe some code in javascript can help !
do you remember my thread called " Dynamic Condition "
==> http://www.thescripts.com/forum/thread691489.html
I'm actually wonna apply the controlled/dependent lists to that code
i.e. after choosing the field --- user will see in the next select statement only the values of that selected field (grouped by to have no duplicates
for fields:
[php]
<?
$sql = "SHOW FIELDS FROM myTable";
$result = mysql_query($sql);
while($row = mysql_fetch_row($result))
{?>
<option value="<?echo $row[0]?>"><?echo $row[0]?></option>
<?}
?>
[/php]
for values:
[php]
<?
$sql = "Select $field FROM myTable GROUP BY $field";
$result = mysql_query($sql);
while($row = mysql_fetch_row($result))
{?>
<option value="<?echo $row[0]?>"><?echo $row[0]?></option>
<?}
?>
[/php]
"like countries and cities" so why you dont do it!!
[html]<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>simple document</title>
<script language='javascript'><!--
//================= generate in PHP =====================================
countries = new Array();
countries["usa"]= new Array("New York","Chicago");
countries["england"]= new Array("london","bristol");
//================= end of PHP generated script ===============================
function secondList(country){
var a = countries[country];
newListHTML='<select>';
for( city in a){
newListHTML+='<option value="'+a[city]+'">'+a[city]+'</option>';
}
newListHTML+='</select>';
document.getElementById('newListDiv').innerHTML= newListHTML;
}
-->
</script>
</head>
<body>
<form action="vartree.php" method='POST'>
<select name="firstList" onchange="secondList(this.value)">
<option value=''></option>
<option value='england'>england</option>
<option value='usa'>usa</option>
</select>
<div id='newListDiv'></div>
</form>
</body>
</html>[/html]
did you mean something like that?
regards
jx2
your code depends on Arrays - but I can't put all of my fields with all of thier unique values in arrays because they are many - approx. of 30 fields with each have between 2 unique values and 50 unique values - maybe more !
so from your code - i've wrote some code - but it didn't work as I need to use the value of the first field in a php code (mysql for the second list)
[php]
<script language='javascript'>
function secondList(field)
{
newListHTML= '$sql = "SELECT 'field' FROM myTable GROUP BY 'field'"';
document.getElementById('newListDiv').innerHTML= newListHTML;
}
</script>
</head>
<body>
<form action="" method='POST'>
<select name="firstList" onchange="secondList(this.value)">
<option value=''></option>
<?
$sql = "SHOW FIELDS FROM myTable";
$result = mysql_query($sql);
while($row = mysql_fetch_row($result))
{?>
<option value="<?echo $row[0]?>"><?echo $row[0]?></option>
<?}
?>
</select>
<div id='newListDiv'>
<select>
<?
$result = mysql_query($sql);
while($row = mysql_fetch_row($result))
{?>
<option value="<?echo $row[0]?>"><?echo $row[0]?></option>
<?}
?>
</select>
</div>
</form>
[/php]
what do you think ? can't this above code be fixed somehow !
your code depends on Arrays - but I can't put all of my fields with all of thier unique values in arrays because they are many - approx. of 30 fields with each have between 2 unique values and 50 unique values - maybe more !
and? whats the problem? juzt use morte arrays :-)
[quoate[can't this above code be fixed somehow ![/quote]
yes it can be - honestly i think is almost done - i cant do it for you
1 u have to learn
2 i have no idea what you really need
3 i am not payed ;-)
4 i helped you as much as is needed
regards
jx2
Heya, coool.
The thing about PHP is that it doesn't "talk" to the browser the way that JavaScript does.
The general flow of a web request is: - The browser sends a request to the server.
- The server loads the requested page and decides what to do with it.
- In the case of a PHP script, it runs the script by PHP and sends the result to the browser.
- The server closes the completed request and then waits patiently for the next one.
Note that once the server sends the page to the client's browser, that's it; to get any more data from the server, you have to send a request for another page. This is the idea behind AJAX; it allows you to send a new request without having to load a new page.
If you want to be able to load a set of data without connecting to the server first, then you have to have loaded that data when you first opened the page. So for example, if you want to populate a select element from a MySQL result set, you have to either: - connect to the server again by using AJAX or submitting a form, or
- have already loaded that data as part of the HTML / JavaScript.
This is what JX2 is trying to get at in his posts.
You can use PHP to format your MySQL result set as a JavaScript object and output that as part of the page.
For example: -
$sql = "
-
SELECT
-
DISTINCT
-
`countries`.`name`
-
AS `country`,
-
`cities`.`name`
-
AS `city`
-
FROM
-
(
-
`countries`
-
LEFT JOIN
-
`cities`
-
USING
-
(`countryid`)
-
)
-
ORDER BY
-
`countries`.`name` ASC,
-
`cities`.`name` ASC";
-
$res = mysql_query($sql);
-
-
$data = array();
-
-
while($row = mysql_fetch_assoc($res))
-
{
-
$data[$row['country']][] = $row['city'];
-
}
-
-
echo json_encode($data);
-
You end up with something very similar to what JX2 proposed as your output.
The other option would be to use AJAX (I promise it's not nearly as scary as it sounds!).
okay from your useful comments :) I'm really near from the final correct solution
now i have a big Array that have all fields and inside this array i have a sub array for each field to present a unique values
my problem now with how to use 2-dim array in javascript
here's the code i reached unitl now: -
<script language='javascript'>
-
-
function secondList(field)
-
{
-
var value;
-
var content = new Array();
-
content = data[field][];
-
newListHTML='<select>';
-
for(value in content)
-
{
-
newListHTML+='<option value="'+content[value]+'">'+content[value]+'</option>';
-
}
-
newListHTML+='</select>';
-
document.getElementById('newListDiv').innerHTML= newListHTML;
-
}
-
</script>
-
here's how the data look like of my array:
array name: $data[][] -
Array
-
(
-
-
[field1] => Array
-
(
-
[0] => value1
-
[1] => value2
-
)
-
[field2] => Array
-
(
-
[0] => value1
-
[1] => value1
-
[2] => value1
-
[3] => value1
-
[4] => value1
-
)
-
.....................................................etc
-
}
I can't get the javascript array working ! .. do you have any clue where is my mistake in the code ? !
Heya, coool.
Where do you create the JavaScript data object?
Oh ! --- should i create it inside my javascript !! how !
data is here inside the php code:
[php]
$sql1 = "SHOW FIELDS FROM TableOne";
$res1 = mysql_query($sql1);
$data = array();
while($row1 = mysql_fetch_row($res1))
{
$sql2 = "SELECT ".$row1[0]." FROM TableOne GROUP BY ".$row1[0];
$res2 = mysql_query($sql2);
while($row2 = mysql_fetch_row($res2))
{
$data[$row1[0]][] = $row2[0];
}
}
[/php]
when I do this:
[php]
echo "<pre>";
print_r($data);
echo "</pre>";
[/php]
,I get this output: -
Array
-
(
-
[field1] => Array
-
(
-
[0] => value1
-
[1] => value2
-
)
-
[field2] => Array
-
(
-
[0] => value1
-
[1] => value1
-
[2] => value1
-
[3] => value1
-
[4] => value1
-
)
-
.................................................. ...etc
-
}
-
i looked at jx2 code !
when he/she created countries array, he didn't declare it inside the javascript !
similar to this , i've created " data " in php and then used it in javascript !
am i wrong :) ?
i looked at jx2 code !
when he/she created countries array, he didn't declare it inside the javascript !
similar to this , i've created " data " in php and then used it in javascript !
am i wrong :) ?
i am HE :-)
you are wrong
i did declare array in javascript
and expected that you create this javascript/arrays in php (in php you can create dynamicly javascript code)
but lets be honest as PBmods sugested thats the job for ajax (to be honest thats the simliest and niciest solution in this case)
jx2
oops
when jx2 wrote inside his javascript portion this: -
//================= generate in PHP =====================================
-
countries = new Array();
-
countries["usa"]= new Array("New York","Chicago");
-
countries["england"]= new Array("london","bristol");
-
//================= end of PHP generated script ===============================
-
it's written: generate in PHP --- so I thought that means these three lines should be generated in PHP not in javascript code
or !! i don't know what does jx2 mean !?
Mr. HE :-)
thanks for explaning
I'm still afraid of AJAX !
can we do it together here ! or should i just stick with trying to solve this code i have until now !!!
Cheers,
SHE :-)
lets be honest its seems you trying to do to much things at a time
if i were you i woul write php/mysql first
one function at a time okey? promise me you re going to learn and we can start
first of all how your table in mysql look like?
:-)
my tables are just the same - same fields - no keys - we don't need to worry about that - and lets concentrate on doing the code for only one table
my form is a query based form - i'm asking the user to fill my query
and the problem here i'm trying to solve is to have a condition/criteria for my query
SELECT $fields FROM $table WHERE $criteria
after WHERE -- we usually have the name of the field then the operator then the value
now ! i know how to populate the fields i have in my table
with this code:
[php]
<select>
<?
$sql = "SHOW FIELDS FROM myTable";
$result = mysql_query($sql);
while($row = mysql_fetch_row($result))
{?>
<option value="<?echo $row[0]?>"><?echo $row[0]?></option>
<?}
?>
</select>
[/php]
and I know how to populate the values of one field - if my $field=field2 - all unique values of field2 will be listed
with this code:
[php]
<select>
<?
$sql = "Select $field FROM myTable GROUP BY $field";
$result = mysql_query($sql);
while($row = mysql_fetch_row($result))
{?>
<option value="<?echo $row[0]?>"><?echo $row[0]?></option>
<?}
?>
</select>
[/php]
i beileve that this is a small problem.. so how can i devided it to smallers :-) !!
Heya, Coool.
Think about it this way.
JavaScript, just like HTML, is evaluated by the browser, not the server.
For example, if you wanted to output a div, you would use code similarly to this: -
echo '<div>some text goes here</div>';
-
Note that you're not actually outputting a DIV. Rather, you're outputting code that tells the browser, "Create a DIV and append a #text child with the value, 'some text goes here'".
Similarly, you can "interact" with javascript : -
echo '
-
<script type="text/javascript">
-
var myName = "', $_SESSION['name'], '";
-
</script>';
-
Note that you're not actually sending $_SESSION['name'] to the browser. When PHP evaluates this code, it will turn it into something like this: -
<script type="text/javascript">
-
var myName = "coool";
-
</script>
-
Note that you're not actually creating the myName variable on the server. Again, you send HTML and JavaScript to the browser, and the *browser* interprets this code and creates the myName variable.
With this in mind, how do we 'transport' your MySQL results from the PHP side to JavaScript?
Fortunately, there's a PHP function that will make 90% of this a lot easier!
Let's start with an example: -
$resultSet = array(
-
'USA' => array(
-
'New York',
-
'Chicago',
-
'Dallas'
-
),
-
-
'Japan' => array(
-
'Tokyo',
-
'Hiroshima'
-
)
-
);
-
-
echo '<script type="text/javascript">
-
var theArray = eval("(" + "', json_encode($resultSet), '" + ")");
-
alert(theArray["USA"][2]);
-
</script>';
-
Here's what PHP actually sends to the browser: -
<script type="text/javascript">
-
var theArray = eval("(" + "{'USA':['New York','Chicago','Dallas'],'Japan':['Tokyo','Hiroshima']}" + ")");
-
alert(theArray["USA"][2]);
-
</script>
-
You can probably tell that I am well-versed in the names of non-US cities :P
I have understand what I tried to implement something in reality - felt reallyyyy sad as I couldn't :(
[php]
echo '<script type="text/javascript">
function secondList(field)
{
var theArray = eval("(" + "', json_encode($data), '" + ")");
var value;
content = theArray[field][];
newListHTML="<select>";
for(value in content)
{
newListHTML+="<option value=\""+content[value]+"\">"+content[value]+"</option>";
}
newListHTML+="</select>";
document.getElementById("newListDiv").innerHTML= newListHTML;
}
</script>';
[/php]
am I near :-s !!
Heya, Coool.
You are very close :)
This line: -
content = theArray[field][];
-
Is not valid syntax in any language. In PHP, you'd be saying, "create a new, empty element in the array and set content equal to it". In Javascript, you'd be saying, "parse error".
Did you mean this instead: -
content = theArray[field];
-
I don't seem that close :(
I've fixed it as you told me - it doesn't work ! well I meant to say an array with 2-dim
here's my code - can you see where's the error !
[php]
<?
$sql1 = "SHOW FIELDS FROM TableOne";
$res1 = mysql_query($sql1);
$data = array();
while($row1 = mysql_fetch_row($res1))
{
$sql2 = "SELECT ".$row1[0]." FROM TableOne GROUP BY ".$row1[0];
$res2 = mysql_query($sql2);
while($row2 = mysql_fetch_row($res2))
{
$data[$row1[0]][] = $row2[0];
}
}
echo '<script type="text/javascript">
function secondList(field)
{
var theArray = new Array();
theArray = eval("(" + "', json_encode($data), '" + ")");
var value;
var content = new Array();
content = theArray[field];
newListHTML="<select>";
for(value in content)
{
newListHTML+="<option value=\""+content[value]+"\">"+content[value]+"</option>";
}
newListHTML+="</select>";
document.getElementById("newListDiv").innerHTML= newListHTML;
}
</script>';
?>
<form action="" method='POST'>
<select name="firstList" onchange="secondList(this.value)">
<option value=''></option>
<?
$sql = "SHOW FIELDS FROM TableOne";
$result = mysql_query($sql);
while($row = mysql_fetch_row($result))
{?>
<option value="<?echo $row[0]?>"><?echo $row[0]?></option>
<?}
?>
</select>
<div id='newListDiv'>
</div>
</form>
[/php]
when I load the page into a browswer -- at the bottom they said there's an error in this page - they meant the javascript thing :(
shall i use AJAX (scaryyy!) or it's too late -- how long will it take !!
Heya, Coool.
I made a few changes. Most notably, I moved theArray outside of the function (since you only need to create it once per page load).
Also notice that the select element has a slightly different onchange.
Otherwise it looks pretty good. If you're still getting an error, post back with the error message, as well as the EVALUATED source of the page (i.e., View Source in your browser, copy-paste). -
<?
-
$sql1 = "SHOW FIELDS FROM TableOne";
-
$res1 = mysql_query($sql1);
-
$data = array();
-
while($row1 = mysql_fetch_row($res1))
-
{
-
$sql2 = "SELECT ".$row1[0]." FROM TableOne GROUP BY ".$row1[0];
-
$res2 = mysql_query($sql2);
-
while($row2 = mysql_fetch_row($res2))
-
{
-
$data[$row1[0]][] = $row2[0];
-
}
-
}
-
-
echo '<script type="text/javascript">
-
var theArray = eval("(" + "', json_encode($data), '" + ")");
-
function secondList(field)
-
{
-
var value, content, newListHTML;
-
content = theArray[field];
-
newListHTML = "<select>";
-
for(value in content)
-
{
-
newListHTML += "<option value=\"" + content[value] + "\">" + content[value] + "</option>";
-
}
-
newListHTML += "</select>";
-
document.getElementById("newListDiv").innerHTML = newListHTML;
-
}
-
</script>';
-
?>
-
-
<form action="" method='POST'>
-
-
<select name="firstList" onchange="secondList(this.options[this.selectedIndex].value)">
-
<option value=''></option>
-
<?
-
$sql = "SHOW FIELDS FROM TableOne";
-
$result = mysql_query($sql);
-
-
while($row = mysql_fetch_row($result))
-
{ ?>
-
<option value="<?echo $row[0]?>"><?echo $row[0]?></option>
-
<? }
-
?>
-
</select>
-
-
<div id='newListDiv'>
-
</div>
-
-
</form>
-
Alright ! the problem doesn't seem to be from the function
but the problem is when i'm "echo"ing the javascript !
but how can i use "data" then !!
example (not working):
[php]
echo '<script type="text/javascript">
function secondList(field)
{
var newListHTML;
newListHTML = "yesss";
document.getElementById("newListDiv").innerHTML = newListHTML;
}
</script>';
<form action="" method='POST'>
<select name="firstList" onchange="secondList(this.options[this.selectedIndex].value);">
...........
.........
...........
</select>
<div id='newListDiv'>
</div>
</form>
[/php]
BUT ! when i do this --- code is workin -- i.e displaying "yessss" when something selected from the firstList !!
example (working):
[php]
<script language='javascript'>
function secondList(field)
{
var newListHTML;
newListHTML = "yesss";
document.getElementById("newListDiv").innerHTML = newListHTML;
}
</script>
<form action="" method='POST'>
<select name="firstList" onchange="secondList(this.options[this.selectedIndex].value);">
...........
.........
...........
</select>
<div id='newListDiv'>
</div>
</form>
[/php]
is there any solution ! .. or shall we give up and try using AJAX :( :S
I told you in my post to break this down into individual problems.
This was your reply
this is not many problems together - it's only one problem called (controlled/dependent 2 lists) where what's selected in one list should be used in mysql query in the second list to get the values of the first list selection
Which has proved to be wrong.
okay then tell me "cold green" what's the sup problems of this problem ??
I really can't think of sub-problems for this problem.. :)
Are we having fun yet?
What does your output look like?
here's the source code - (from the browser) -
<script type="text/javascript">
-
var theArray = eval("(" + "{"field1":["value1"],"field2":["value1","value2","value3","value4","value5"],"field3":["value1","value2","value3","value4","value5"],"field4":["value1","value2","value3"]}" + ")");
-
function secondList(field)
-
{
-
var value, content, newListHTML;
-
content = theArray[field];
-
newListHTML = "<select>";
-
for(value in content)
-
{
-
newListHTML += "<option value=\"" + content[value] + "\">" + content[value] + "</option>";
-
}
-
newListHTML += "</select>";
-
document.getElementById("newListDiv").innerHTML = newListHTML;
-
}
-
</script>
-
-
<form action="" method='POST'>
-
<select name="firstList" onchange="secondList(this.options[this.selectedIndex].value);">
-
<option value=''></option>
-
<option value="field1">field1</option>
-
<option value="field2">field2</option>
-
<option value="field3">field3</option>
-
<option value="field4">field4</option>
-
</select>
-
<div id='newListDiv'></div>
-
</form>
-
yeah I'm having fun :) , but this will be more fun if we find the solution ;)
Heya, Coool.
Change this line in your source: -
var theArray = eval("(" + "', json_encode($data), '" + ")");
-
To: -
var theArray = eval("(" + \'', json_encode($data), '\' + ")");
-
same thing :(
nothing working..
any clue, guys ?
I really need some help..
Heya, Coool.
What error are you getting?
no error is displayed !!
it's java.. they say there's an error - at the bottom-bar of the browser - but they dont' say what's wrong ! .. it just mean there's something wrong with javascript..
i've copied and pasted here / above / the source code from the browser ..
what do you think !! .. can you see where is the error !
maybe if you tried my code using one of a database table you have !! , you can find the error :) !
any clue, guys ?
I really need some help..
hey im here ;-)
pbmods gave you answer - i try to explain it to you :-)
[php]
// whats wrong with that?
echo "very important guy said"i am god" thatwhat he said";
// you got error cos you closing quotation mark "very important guy said"
// and after that "computer" expect ';' or '.'
// so becose that is wrong we need to tell "computer"
// that this is not speach mark so we do \"
// backslash tells "computer" do not worry about next sign its not important
// for you its onty a part of string
//so
echo "very important guy said \"i am your god\" that what he said";
//got it? php will output "
[/php]
other special characters are \n \t \r \' \"
i know its a bit fuzzy explenation but i did my best :-]
regardz
jx2
no error is displayed !!
it's java.. they say there's an error - at the bottom-bar of the browser - but they dont' say what's wrong ! .. it just mean there's something wrong with javascript..
they also said the line number of the error and character
if that java script just check sorce of the page to see if you did good job in php
my guess is \"
hey jx2 -- long time no seen !
hmmm,
so u're saying there's something wrong with this:
[php]
echo '<script type="text/javascript">
var theArray = eval("(" + \'', json_encode($data), '\' + ")");
</script>';
[/php]
hmmmmmmmmmm.......
shouldn't it be like this:
[php]
echo '<script type="text/javascript">
var theArray = eval(\"(\" + \' ', json_encode($data), ' \' + \")\");
</script>';
[/php]
here's the error I'm getting when I load the page (browser
--- only this .. trust meee :-)
trust me it says which line it is ;-) lol
just click on this yellow triangle
[php]echo '<script type="text/javascript">
var theArray = eval("(" + \'', json_encode($data), '\' + ")");
</script>';[/php]
well you need to know which one you want to "print" ( to be marked \ )
this above look like a mess to me :-)
lol, calm down... be cooooool :P
I'll try now.. brb in few minutes :D
ahaaaaaaaaaaaa
they're saying
in this line:
[php]
<script>
var theArray = eval("("+',json_encode($data),'+")");
</script>
[/php]
that the error is .... missing ']' at character 1
strange error !!
HEY HEY
I HAVE FIXED IT
can't beilve ittttt .. .
wooooow
finaaaallyyyyy
okay here's what made things workinggggg :DDDD
[php]
<script>
var theArray = eval(',json_encode($data),');
<script>
[/php]
THANKS very much for your helppp PBmods and jx2 : ) : ) : ) : )
<script>
var theArray = eval("("+',json_encode($data),'+")");
</script>
LOL
lol lol
and you dont know whats wrong with that? lol
hehe
i'm not sure youreally need eval() function here ... it would just print
Array("var1","var2".... ,"varX"); insted - but that different story
json_encode() is... rather php function not a javascript a specialy that you using $data :-)
you need to ask yourself question - what did i want to print in this place
(i know it should be array) read about it here
and now simply answers :-) lol
1. you didnt print what is needed - you need to use \ so you get in this place something what look like
var theArray = eval("(" + DATA TEXT HERE + ")");
2. coma is not a dot look here
"this is string".aPHPfunction()."string".$phpVariable;
in other world dot is a plus sign for to use with strings
i hope this is not clear ... learn ... read... and ask...
regards jx2
...
Ohhhh right!
:P
I feel kinda silly now.
See, using the eval() function is only necessary when returning from an AJAX call! You can actually just insert your json_encode()'ed data directly into your JavaScript, since it outputs valid JavaScript.
*sigh* It's been a long week.
At any rate, glad to hear you got it working! Good luck with your project, and if you ever need anything, post back anytime :)
You guys are wonderful - I wish I know 1000000 people like both of you :-)
now.. I've a little question !
with this technique we used in this post... and with the AJAX technique...
is it always.......... take long in loading the page ??
as we are loading all the array in the source code (when u see in the browser) !!
or ... do you say that AJAX is faster !!
You guys are wonderful - I wish I know 1000000 people like both of you :-)
now.. I've a little question !
with this technique we used in this post... and with the AJAX technique...
is it always.......... take long in loading the page ??
as we are loading all the array in the source code (when u see in the browser) !!
or ... do you say that AJAX is faster !!
all depends
if you got many options (as you have) probably ajax is faster
but if you got just a few categories i wouldnt boder with ajax (you would have to wait for response frome server when you choose something
how big is your page after loading?
pbmods - are we using ajax here? its so long post that i ve got lost :-)
Heya, Coool.
Since you seem enthralled with the idea of integrating AJAX into your script, here's how your page would work if you integrated AJAX functionality: - When the User selects an option from the first select element, the browser calls a JavaScript function that creates a new AJAX object (also [properly] known as an XmlHttpRequest object).
- The AJAX function sends a request to the server for a separate page (this is key) that takes in a parameter and returns ONLY the JavaScript needed to populate the second select.
For example, the AJAX call might send a request for http://your-site.tld/selector.php?cat=US and get back something like '["New York","Chicago","Dallas"]', which can be eval()'ed into a JavaScript Array. - From there, you do pretty much the same thing that you're doing now.
The benefits of using AJAX here: - You're loading the extra data *after* the page is finished loading, which speeds up the entire page load slightly.
- The total load on your server is reduced slightly, as you don't have to send as much data.
- If your database gets REALLY big, these savings will start becoming much more significant (on the order of seconds instead of nanoseconds).
- You can cache results on the User's computer in a cookie to speed up execution time even more.
A couple of cons of using AJAX: - Unless you use intelligent prefetching methods, there will be a delay between when the User selects the option and when the second select becomes available.
- Prefetching means that you may actually end up loading even *more* data than you really need because you don't know what the User will do next.
Still, AJAX is a fun way to make impressive applications. To get started, hop on over to this article, and be sure to post your questions in our JavaScript forum if you ever get stuck!
Good luck with your project, and if you ever need anything, post back anytime :)
Good explainations, thanks
I'll go to the javascript forum......... as this post is reallyyyy long !!
see you there guys :-)
how big is your page after loading?
really really big ------ like more than 50 000 distinct rows -- and it's increasing in a daily basis !! :-S
Sign in to post your reply or Sign up for a free account.
Similar topics
by: Tony Grider |
last post by:
I am trying to find a way to create dependent dropdown lists in C# The old
way I knew involved javascript and will no longer work in the new design. I
need for each list to be database driven (data...
|
by: Phil Howard |
last post by:
I'm actually getting the mailing list mail, so I don't know what the deal is.
Successful deliveries are coming from 64.117.225.209. But 207.173.200.206 has
big problems. Sendmail is misconfigured...
|
by: Galina |
last post by:
Hello
I have 6 dependent list boxes on my ASP page:
Faculty;
Lecturer;
Course;
Course occurrence;
Group;
Week commencing date.
When faculty is selected, lists of lecturers and...
|
by: Mark |
last post by:
Hi, I have two select boxes, like country and province.
When a user select a country the list of provinces should change.
How might one go about doing this?
|
by: rodeoval |
last post by:
I need to have three drop down lists, but the dependent should get the values from the database without refreshing the page..If knows,someone pls reply soon
|
by: jdkhan |
last post by:
i want to use two lists one dependent on other just like city dependent on country selection
how can i do this in single page using PHP
|
by: avigiano |
last post by:
Good morning. I have a contacts database that tracks the regular things like phone numbers, address etc. User searches for contacts through a combo box that lists entires by last name.
I've...
|
by: Bels |
last post by:
I am currently designing a real estate website using Dreamweaver CS3, php, MySQL on a Mac. On it is a 'property search' form that queries the property database. The form consists of 5 dropdown lists....
|
by: jmartmem |
last post by:
Greetings,
I have an ASP page with two dynamic dependent list boxes written in JavaScript. My dependent lists work great, but my problem is that the values for "Program_Name" and "Project_Name"...
|
by: emmanuelkatto |
last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud.
Please let me know.
Thanks!
Emmanuel
|
by: BarryA |
last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
by: Sonnysonu |
last post by:
This is the data of csv file
1 2 3
1 2 3
1 2 3
1 2 3
2 3
2 3
3
the lengths should be different i have to store the data by column-wise with in the specific length.
suppose the i have to...
|
by: Hystou |
last post by:
There are some requirements for setting up RAID:
1. The motherboard and BIOS support RAID configuration.
2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers,...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
| |