/    Sign up×
Community /Pin to ProfileBookmark

loading selected option on hierachical select boxes

I realise that the subject of hierachical select boxes has come up on this forum a few times in the past but I need help on an elaboration of it. I think this is quite difficult so any help greatly appreciated.

I have 2 select boxes. the box on the left dictates content of box on the right.
[URL]http://www.holdenandco.co.uk/public/selectboxproblem.html[/URL]

Problem lies with setting which option will be selected when the page loads. I have succesfully used PHP to go through an array, when it finds the value in the array which matches a varaible’s value which is drawn from a sql database PHP gets the index of its array and stores that as a variable. I then just print (“var n= that PHP variable”) so to speak.
so now when the client side stuff starts we have eg var n=1 half-way down the javascript code on the link above. this is then compared to the index value of the javascript array when writing out the select box code and if the javascript array’s index value is the same as the n variable then it wirtes <option selected.. instead of just <option..

this works fine BUT… I need to do the same thing on the second drop down box. the PHP will bring back the index number of the second select boxes VALUE array index number. If they are equal (and they can only be equal if the corresponding left select box has the appropriate selection)
then I want it to again write <option selected.. instead of just <option.. for that particular <option>.

Any ideas anyone? ?
just to make clear that the php is not a problem, this is just a javascript problem, only mentioned the php for completeness.

My unsuccesful attempt, (which could be a long way from working) is here:

[URL]http://www.holdenandco.co.uk/public/selectboxproblemmyattempt.html[/URL]

to post a comment
JavaScript

18 Comments(s)

Copy linkTweet thisAlerts:
@FangSep 06.2003 — You wrote:
then I want it to again write <option selected.. instead of just <option.. for that particular <option>. [/QUOTE]
Do you mean the 2nd select box?

The fact that an option has been selected, it's index is known.
Copy linkTweet thisAlerts:
@baranauthorSep 06.2003 — Fang,

yes I do mean the second box. The first box works fine in the page on the first link in my above post.

I want the document.writeln method to write <option selected> for the option that has been selected on another PHP page. In practice this means returning an index number from the PHP to the javascript, declaring this number as a variable, say var = n, then document.writeln() 'ing <option selected> instead of <option> for the option where the javascript array index value [i] is equal to n.



I've got it work on the first box. (note that n=1 in the code and therefore the left drop-down loads with the second, not the first, option selected by default). but I need to be able to do the same with the right drop-down.



any ideas?



Thanks.
Copy linkTweet thisAlerts:
@FangSep 06.2003 — Take a look at this, it creates the second list dynamically.

Once an item has been chosen from the second list, the value of "n" is changed accordingly.

I am not sure if this was your intention, but it's a base to work from.

Note: all those writeln statements are unnecessary and time consuming.
[code=php]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>dynamic select lists</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />

<script type="text/javascript">
//<![CDATA[
<!--
function changeMenu(idx) {
var Obj=document.MyForm.SelectSecondary;
//alert(Obj.options.length);
//delete options
for(var i=Obj.options.length; i>=0; i--) {
Obj.options[i]=null;
}
//add options
for(i=0; i<subopt[idx].length; i++) {
Obj.options[i]=new Option(subopt[idx][i], i);
}
}

var n = 0; // initilize first select
var catopt = ["Main Option 1","Main Option 2","Main Option 3"];
var subopt = [];
subopt[0] = ["Sub-option value 1","Sub-option value 2","Sub-option value 3","Sub-option value 4"];
subopt[1] = ["Sub-option value 5","Sub-option value 6"];
subopt[2] = ["Sub-option value 7","Sub-option value 8","Sub-option value 9","Sub-option value 10"];

//optionName = new Option([text, value, defaultSelected, selected])

var tbl='<FORM NAME="MyForm"><TABLE BORDER = 0 BGCOLOR = "#F8D85A" CELLPADDING = 3 CELLSPACING = 0>'+
'<TR><TD COLSPAN = 3><FORM NAME = "SelectMenu">'+
'<FONT SIZE = 4 FACE = "Times">'+
'</TD></TR><TR><TD ALIGN = LEFT>'+
'<FONT SIZE = 2 FACE = "Times" >Main Menu</FONT><BR>'+
'<SELECT NAME="SelectPrimary" onChange="changeMenu(this.options[this.selectedIndex].value);">';
for(var i=0; i<catopt.length; i++) {
if(i==n) {
tbl+='<OPTION VALUE="'+i+'" SELECTED>'+catopt[i];
}
else {
tbl+= '<OPTION VALUE="'+i+'">'+catopt[i];
}

}
tbl+='</SELECT></TD><TD><FONT SIZE = 2 FACE = "Times" >Sub- Menu</FONT><BR>'+
'<SELECT NAME="SelectSecondary" onChange="n=this.options[this.selectedIndex].value;alert(&quot;n=&quot;+n);">';
tbl+='</TD><TD VALIGN = BOTTOM></TD></TR></FORM></TABLE>';
document.write(tbl);
// Initilize "SelectSecondary"
changeMenu(n);
//-->
//]]>
</script>

</head>
<body>
</body>
</html>
[/code]
Copy linkTweet thisAlerts:
@baranauthorSep 07.2003 — Fang,

Some beautiful looking code there, but I have to be honest I don't quite understand how its writing the second select box. sorry!

What I want is for it to be able to write the form, when the page loads, with an option from the second select box already selected.

Lets say the index value of the selected option of the second select box when the page loads is equal to a new variable I declare, called n2. Just as if you declare var n=1 in the code then the first select box will load with 'main option 2' selected. I want to be able to declare a value for n2,eg var n2 =1 and the appropriate option be selected in the second select box when the page loads for the first time.

so lets say we set n =1 and n2 = 1 then the fiirst select box would display 'main option 2' and the second select box would display 'sub-option 6'.
Copy linkTweet thisAlerts:
@FangSep 07.2003 — The second list is dynamically written according to the choise in the first list. n and n2 are changed when the lists are changed.

There is no check on n2 being too large/small for the length of the second list.
[code=php]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>dynamic select lists</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />

<script type="text/javascript">
//<![CDATA[
<!--
function changeMenu(idx) {
//change n
n=idx;
var Obj=document.MyForm.SelectSecondary;
//delete options
for(var i=Obj.options.length; i>=0; i--) {
Obj.options[i]=null;
}
//add options
for(i=0; i<subopt[idx].length; i++) {
if(i==n2) {
Obj.options[i]=new Option(subopt[idx][i], i, false, true);
}
else {
Obj.options[i]=new Option(subopt[idx][i], i);
}
}
}

var n = 1; // initilize first select
var n2=1; // initilize second list
var catopt = ["Main Option 1","Main Option 2","Main Option 3"];
var subopt = [];
subopt[0] = ["Sub-option value 1","Sub-option value 2","Sub-option value 3","Sub-option value 4"];
subopt[1] = ["Sub-option value 5","Sub-option value 6"];
subopt[2] = ["Sub-option value 7","Sub-option value 8","Sub-option value 9","Sub-option value 10"];

var tbl='<FORM NAME="MyForm"><TABLE BORDER = 0 BGCOLOR = "#F8D85A" CELLPADDING = 3 CELLSPACING = 0>'+
'<TR><TD COLSPAN = 3><FORM NAME = "SelectMenu">'+
'<FONT SIZE = 4 FACE = "Times">'+
'</TD></TR><TR><TD ALIGN = LEFT>'+
'<FONT SIZE = 2 FACE = "Times" >Main Menu</FONT><BR>'+
'<SELECT NAME="SelectPrimary" onChange="changeMenu(this.options[this.selectedIndex].value);">';
for(var i=0; i<catopt.length; i++) {
if(i==n) {
tbl+='<OPTION VALUE="'+i+'" SELECTED>'+catopt[i];
}
else {
tbl+= '<OPTION VALUE="'+i+'">'+catopt[i];
}

}
tbl+='</SELECT></TD><TD><FONT SIZE = 2 FACE = "Times" >Sub- Menu</FONT><BR>'+
'<SELECT NAME="SelectSecondary" onChange="n2=this.options[this.selectedIndex].value;alert(&quot;n2=&quot;+n2);">';
tbl+='</TD><TD VALIGN = BOTTOM></TD></TR></FORM></TABLE>';
document.write(tbl);
// Initilize "SelectSecondary"
changeMenu(n);
//-->
//]]>
</script>
</head>
<body>
</body>
</html>
[/code]
Copy linkTweet thisAlerts:
@baranauthorSep 07.2003 — Fang,

I sincerely appreciate you taking your time to try and help me but I think we're talking past each other here.

The second drop down box cannot be written dynamically when the user changes the first select box option because I need the second select box option to be selected when the page is loaded. The script you wrote doesn't alter which of the second select boxes options is already selected when the page is loaded.

Does this make any sense?

Thanks.
Copy linkTweet thisAlerts:
@FangSep 07.2003 — On loading the selection is determined by the variables n and n2, which are the indices to the boxes. These are both set as the "selected" item.
Copy linkTweet thisAlerts:
@baranauthorSep 07.2003 — In theory yes. but there's a problem. its loading as if n2 = 0 even when its set to 1 as in your code above.

again thanks for your time. I can't see what the problem is myself, but I can just about see how your code works now.
Copy linkTweet thisAlerts:
@FangSep 08.2003 — It was just IE misbehaving again :mad:

Just replace this function:
[code=php]
function changeMenu(idx) {
//change n
n=idx;
var Obj=document.MyForm.SelectSecondary;
//delete options
for(var i=Obj.options.length; i>=0; i--) {
Obj.options[i]=null;
}
//add options
for(i=0; i<subopt[idx].length; i++) {
Obj.options[i]=new Option(subopt[idx][i], i);
}
Obj.options[n2].selected=true;
}
[/code]
Copy linkTweet thisAlerts:
@baranauthorSep 08.2003 — BRILLIANT!

thnaks very much. I just added one extra function in so that the value of n2 is changed back to 0 if the first select boxes selection is changed by the user. this way if they move from selecting 'main option 2' to selecting 'main option 3' n2 is changed back to 0.

[code=php]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>dynamic select lists</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />

<script type="text/javascript">
//<![CDATA[
<!--

//small addition to the code
function changen2() {
if (n2!==0) {
n2=0;
}
}

function changeMenu(idx) {
//change n

n=idx;
var Obj=document.MyForm.SelectSecondary;
//delete options
for(var i=Obj.options.length; i>=0; i--) {
Obj.options[i]=null;
}
//add options
for(i=0; i<subopt[idx].length; i++) {
Obj.options[i]=new Option(subopt[idx][i], i);
}

Obj.options[n2].selected=true;
}


var n = 1; // initilize first select
var n2=1; // initilize second list
var catopt = ["Main Option 1","Main Option 2","Main Option 3"];
var subopt = [];
subopt[0] = ["Sub-option 1","Sub-option 2","Sub-option 3","Sub-option 4"];
subopt[1] = ["Sub-option 5","Sub-option 6"];
subopt[2] = ["Sub-option 7","Sub-option 8","Sub-option 9","Sub-option 10"];

var tbl='<FORM NAME="MyForm"><TABLE BORDER = 0 BGCOLOR = "#F8D85A" CELLPADDING = 3 CELLSPACING = 0>'+
'<TR><TD COLSPAN = 3><FORM NAME = "SelectMenu">'+
'<FONT SIZE = 4 FACE = "Times">'+
'</TD></TR><TR><TD ALIGN = LEFT>'+
'<FONT SIZE = 2 FACE = "Times" >Main Menu</FONT><BR>'+
'<SELECT NAME="SelectPrimary" onChange="changen2(this.options[this.selectedIndex].value); changeMenu(this.options[this.selectedIndex].value)">';
for(var i=0; i<catopt.length; i++) {
if(i==n) {
tbl+='<OPTION VALUE="'+i+'" SELECTED>'+catopt[i];
}
else {
tbl+= '<OPTION VALUE="'+i+'">'+catopt[i];
}

}
tbl+='</SELECT></TD><TD><FONT SIZE = 2 FACE = "Times" >Sub- Menu</FONT><BR>'+
'<SELECT NAME="SelectSecondary" onChange="n2=this.options[this.selectedIndex].value;alert(&quot;n2=&quot;+n2);">';
tbl+='</TD><TD VALIGN = BOTTOM></TD></TR></FORM></TABLE>';

document.write(tbl);
// Initilize "SelectSecondary"
changeMenu(n);
//-->
//]]>
</script>
</head>
<body>
</body>
</html>
[/code]


now all I have to do is add the value="" part to the second select boxes options (names are different to the values in this select box), could you give me a hint on how to do this?

Thanks very much for all your help. Sincerely!
Copy linkTweet thisAlerts:
@FangSep 08.2003 — In the function changeMenu() for the add options, the basic structure is:

[COLOR=green]optionName = new Option([text, value, defaultSelected, selected])[/COLOR]

so instead of: Obj.options[i]=new Option(subopt[idx][i], i);

your could do:

Obj.options[i]=new Option(subopt[idx][i], subvalue[idx][i]);

The [COLOR=green]defaultSelected and selected [/COLOR] are not used in this instance.
Copy linkTweet thisAlerts:
@baranauthorSep 08.2003 — so this is the syntax of a new option function:

new Option([text[, value[, defaultSelected[, selected]]]])

I assume you don't have to use the square brackets from Fang's example.

My example was a bit too simple. What I actually need is for the second select box to be a bit like this:

<select name="SelectSecondary">

<option value="a very long piece of text">short piece of text</option>

<option value="another very long piece of text">another short piece of text</option>

<option value="yet another very long piece of text">yet another short piece of text</option>

</select>

The text of the option boxes and their respective values are unrelated to each other, and neither the text nor the value for each option contains a number which could be an index number from the array.

So this means that I need to seriously re-write the above code to get it to work. Additionally I really need n2 to have values stretching from 0 to 9. All in all maybe its better I go back to modifying my original script now I have a bit more of an idea of what I'm doing.
Copy linkTweet thisAlerts:
@baranauthorSep 08.2003 — actually on second thoughts n2 can have values as it does now. can just alter some things in my PHP to work around it.
Copy linkTweet thisAlerts:
@FangSep 08.2003 — The option values can be anything. The index is just an index,

it has nothing to do with the actual content of the select box, weather that be the value or text of the option.

The index is used to work on the select box.
Copy linkTweet thisAlerts:
@baranauthorSep 08.2003 — I must have been typing my 12th post as you were typing your 391st post, bit of a mix-up.

Anyway thats very clear and should be all the info I need- it took a while but I'm finally there. Thanks once again.
Copy linkTweet thisAlerts:
@baranauthorSep 08.2003 — Fang,

Are you there? I guess you thought you'd got rid of me...but alas, I'm back. or calling anyone else who can help.

My (or should that be Fang's!) javascript is on the verge of perfection but I'm a little stuck on one last thing. I want the value of the option selected in the right select box to be printed out below the form. I can get this value to appear in an alert box exactly when I want (when the page loads, and when any of the options are changed) but I can't get the value (declared in the TextDisplay variable) to be written to the page. clearly its down to my poor understanding of the dom somewhere along the line, but what?

I get an error saying the div element I'm trying to write to can't be found. I've commented around the code that needs to be uncommented for my script to reach its final state. Can anyone see how to get this beauty working?

Thanks...

[code=php]<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>dynamic select lists</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />

<script type="text/javascript">
//<![CDATA[
<!--

//small addition to the code
function changen2() {
if (n2!==0) {
n2=0;
}
}

function changeMenu(idx) {
//change n

n=idx;
var Obj=document.MyForm.SubStage;
//delete options
for(var i=Obj.options.length; i>=0; i--) {
Obj.options[i]=null;
}
//add options
for(i=0; i<subopt[idx].length; i++) {
Obj.options[i]=new Option(subopt[idx][i], subvalue[idx][i]);
}

Obj.options[n2].selected=true;
var TextDisplay = Obj.options[n2].value;
// *****************************************************
// help - how do I uncomment the line below and get it to work properly?
//document.getElementById('div1').firstChild.data=TextDisplay;
alert (TextDisplay);
}
// ******************************************************

function updatetext(TextDisplay) {
// *******************************************************
// help - how do I uncomment the line below and get it to work properly?
//document.getElementById('div1').firstChild.data=TextDisplay;
alert (TextDisplay);
}
// *****************************************************************
var n = 1; // initilize first select
var n2=1; // initilize second list
var catopt = ["Main Option 1","Main Option 2","Main Option 3"];
var subopt = [];
subopt[0] = ["Sub-option 1","Sub-option 2","Sub-option 3","Sub-option 4"];
subopt[1] = ["Sub-option 5","Sub-option 6"];
subopt[2] = ["Sub-option 7","Sub-option 8","Sub-option 9","Sub-option 10"];
var subvalue = [];
subvalue[0] = ["Sub-option value 1","Sub-option value 2","Sub-option value 3","Sub-option value 4"];
subvalue[1] = ["Sub-option value 5","Sub-option value 6"];
subvalue[2] = ["Sub-option value 7","Sub-option value 8","Sub-option value 9","Sub-option value 10"];

var tbl='<FORM NAME="MyForm"><TABLE BORDER = 0 BGCOLOR = "#F8D85A" CELLPADDING = 3 CELLSPACING = 0>'+
'<TR><TD COLSPAN = 3><FORM NAME = "SelectMenu">'+
'<FONT SIZE = 4 FACE = "Times">'+
'</TD></TR><TR><TD ALIGN = LEFT>'+
'<FONT SIZE = 2 FACE = "Times" >Main Menu</FONT><BR>'+
'<SELECT NAME="OverallStage" onChange="changen2(this.options[this.selectedIndex].value); changeMenu(this.options[this.selectedIndex].value)">';
for(var i=0; i<catopt.length; i++) {
if(i==n) {
tbl+='<OPTION VALUE="'+i+'" SELECTED>'+catopt[i];
}
else {
tbl+= '<OPTION VALUE="'+i+'">'+catopt[i];
}

}
tbl+='</SELECT></TD><TD><FONT SIZE = 2 FACE = "Times" >Sub- Menu</FONT><BR>'+
'<SELECT NAME="SubStage" onChange="n2=this.options[this.selectedIndex].value; updatetext(this.options[this.selectedIndex].value)">';
tbl+='</TD><TD VALIGN = BOTTOM></TD></TR></FORM></TABLE>';

document.write(tbl);
// Initilize "SubStage"
changeMenu(n);
//-->
//]]>
</script>
</form>
<div id ="div1"> </div>
</body>
</html>
[/code]
Copy linkTweet thisAlerts:
@FangSep 09.2003 — You were trying to write to an element that did not exist.

The function changeMenu is now called from the onload event.

The div (id="div1") must contain some text initially for it's textnode to exist.
[code=php]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>dynamic select lists</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
</head>
<body onload="changeMenu(n);">

<script type="text/javascript">
//<![CDATA[
<!--

//small addition to the code
function changen2() {
if (n2!==0) {
n2=0;
}
}

function changeMenu(idx) {
//change n

n=idx;
var Obj=document.MyForm.SubStage;
//delete options
for(var i=Obj.options.length; i>=0; i--) {
Obj.options[i]=null;
}
//add options
for(i=0; i<subopt[idx].length; i++) {
Obj.options[i]=new Option(subopt[idx][i], subvalue[idx][i]);
}

Obj.options[n2].selected=true;
var TextDisplay = Obj.options[n2].value;
// *****************************************************
// help - how do I uncomment the line below and get it to work properly?
document.getElementById('div1').firstChild.data=TextDisplay;
alert (TextDisplay);
}
// ******************************************************

function updatetext(TextDisplay) {
// *******************************************************
// help - how do I uncomment the line below and get it to work properly?
document.getElementById('div1').firstChild.data=TextDisplay;
alert (TextDisplay);
}
// *****************************************************************
var n = 1; // initilize first select
var n2=1; // initilize second list
var catopt = ["Main Option 1","Main Option 2","Main Option 3"];
var subopt = [];
subopt[0] = ["Sub-option 1","Sub-option 2","Sub-option 3","Sub-option 4"];
subopt[1] = ["Sub-option 5","Sub-option 6"];
subopt[2] = ["Sub-option 7","Sub-option 8","Sub-option 9","Sub-option 10"];
var subvalue = [];
subvalue[0] = ["Sub-option value 1","Sub-option value 2","Sub-option value 3","Sub-option value 4"];
subvalue[1] = ["Sub-option value 5","Sub-option value 6"];
subvalue[2] = ["Sub-option value 7","Sub-option value 8","Sub-option value 9","Sub-option value 10"];

var tbl='<FORM NAME="MyForm"><TABLE BORDER = 0 BGCOLOR = "#F8D85A" CELLPADDING = 3 CELLSPACING = 0>'+
'<TR><TD COLSPAN = 3><FORM NAME = "SelectMenu">'+
'<FONT SIZE = 4 FACE = "Times">'+
'</TD></TR><TR><TD ALIGN = LEFT>'+
'<FONT SIZE = 2 FACE = "Times" >Main Menu</FONT><BR>'+
'<SELECT NAME="OverallStage" onChange="changen2(this.options[this.selectedIndex].value); changeMenu(this.options[this.selectedIndex].value)">';
for(var i=0; i<catopt.length; i++) {
if(i==n) {
tbl+='<OPTION VALUE="'+i+'" SELECTED>'+catopt[i];
}
else {
tbl+= '<OPTION VALUE="'+i+'">'+catopt[i];
}

}
tbl+='</SELECT></TD><TD><FONT SIZE = 2 FACE = "Times" >Sub- Menu</FONT><BR>'+
'<SELECT NAME="SubStage" onChange="n2=this.options[this.selectedIndex].value; updatetext(this.options[this.selectedIndex].value)">';
tbl+='</TD><TD VALIGN = BOTTOM></TD></TR></FORM></TABLE>';

document.write(tbl);
// Initilize "SubStage"

//-->
//]]>
</script>
</form>
<div id ="div1">text(node)</div>
</body>
</html>
[/code]
Copy linkTweet thisAlerts:
@baranauthorSep 09.2003 — excellent stuff. works a treat now. thanks for all your help.
×

Success!

Help @baran spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.11,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...