JS wrote:
"Evertjan." <ex************ **@interxnl.net > skrev i en meddelelse
news:Xn******** ***********@194 .109.133.242...
JS wrote on 30 mei 2005 in comp.lang.javas cript:
function createFirstMenu (sel){
sel = document.getEle mentById('sel1' );
resetMenu(sel);
}
Not that it matters,
but why enter a parameter in the local variable
sel
--- function createFirstMenu (sel){
and then immediately changing the content to
document.getE lementById('sel 1');
--- sel = document.getEle mentById('sel1' );
?
I have this form:
<body onload="createF irstMenu('sel1' );">
<form name="sels" method="post" action="?page=j ubii">
Kategori:
<select name="sel1" id="sel1" onchange="creat eSecondMenu('se l1','sel2',
'sel3');">
</select>
...
.
.
.
But for some reason I don't get access to sel1 in createFirstMenu if I don't
explicitly grap it with:
sel = document.getEle mentById('sel1' );
Guess I am missing something?
The local variable 'sel' is created here:
function createFirstMenu (sel){
It is passed the string 'sel1' from the onload event:
<body onload="createF irstMenu('sel1' );">
The content of 'sel' is replaced with a reference to the element
with id 'sel1' using a hard-coded parameter:
sel = document.getEle mentById('sel1' );
which seems to ignore the value passed to sel in the first place. To
re-use the local variable 'sel', then:
sel = document.getEle mentById(sel);
would make more sense, but probably better would be to use the forms
collection and reduce reliance on getElementById (although it is
supported by perhaps 95% of browsers in use):
sel = document.forms['sels'].elements[sel];
or a reference to the required element could be passed directly from
the onload event:
<body onload="
createFirstMenu (document.forms['sels'].elements['sel1']);
">
Thereby removing the hard-coded values from the script. Having gone
that far, the usefulness of createFirstMenu () becomes moot, since all
it does is call resetMenu() - the onload is effectively:
<body onload="
resetMenu(docum ent.forms['sels'].elements['sel1']);
">
The resetMenu() function is:
function resetMenu(sel){
sel.length = 0;
opt = document.create Element('OPTION ');
sel.appendChild (opt);
opt.value = "";
opt.text = "-- Choose--";
}
When modifying the length of the select to change the number of
options, it seems appropriate to set it to the new length directly:
sel.length = 1;
and then modify the remaining option(s):
sel[0].value = "";
sel[0].text = "-- Choose--";
so now you have:
function resetMenu(sel){
sel.length = 1;
sel[0].value = "";
sel[0].text = "-- Choose--";
}
If there are many option attributes to modify, it may be better
(faster) to create a local variable with a reference to the option:
function resetMenu(sel){
sel.length = 1;
var s = sel[0];
s.value = "";
s.text = "-- Choose--";
//...
}
--
Zif