By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
458,193 Members | 1,648 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 458,193 IT Pros & Developers. It's quick & easy.

Writing Arrays To <select> Tag

P: n/a
Hello everyone.

I'm currently learning Javascript and doing a few exercises.

One problem I'm working on takes an array of names from an xml file using
Ajax and writes it to <select<optionstags.

This is the code they use:

function writeSelect(name_group) {
var this_option;
var my_select = document.getElementById("namelist");
for (var loop = 0; loop < name_group.length; loop++)
{
this_option = new Option();
this_option.value = the_array[loop];
this_option.text = the_array[loop]
my_select.options[loop] = this_option;
}

}
The parameter for writeSelect() function contains the array of names and the
id "namelist" is the id for the select tag in the form element.

This is my first time seeing the new Option() function. Is this the standard
for writing arrays to the <selecttag? Or could this have been done another
way - if so what this that way?

Any response would be appreciated.

--
Message posted via WebmasterKB.com
http://www.webmasterkb.com/Uwe/Forum...cript/200806/1

Jun 27 '08 #1
Share this Question
Share on Google+
12 Replies


P: n/a
LayneMitch wrote:
One problem I'm working on takes an array of names from an xml file using
Ajax and writes it to <select<optionstags.

This is the code they use:

function writeSelect(name_group) {
* *var this_option;
* *var my_select = document.getElementById("namelist");
* *for (var loop = 0; loop < name_group.length; loop++)
* * * {
* * * * this_option = new Option();
* * * * this_option.value = the_array[loop];
* * * * this_option.text = the_array[loop]
* * * * my_select.options[loop] = this_option;
* * * }
}

The parameter for writeSelect() function contains the array of names and the
id "namelist" is the id for the select tag in the form element.

This is my first time seeing the new Option() function. Is this the standard
for writing arrays to the <selecttag? Or could this have been done another
way - if so what this that way?
I'm afraid your function has a number of shortcomings.

- A better backwards compatibility can be obtained by using
'document.forms[0].elements["namelist"]' in stead of
'document.getElementById("namelist")'.
- I surmise that your 'the_array' should read 'name_group'
- It appears you want to do a full refill of the list, since you start
looping from zero. But if your first list would be bigger than the new
one, the last entries of the first list will still be shown. It would
be better to empty the list first and then assign the new ones.
- Inside the loop, you use four lines of code for what is usually done
in one instruction.

All together:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/1999/REC-html401-19991224/strict.dtd">
<html>
<head>
<script type="text/javascript">
var arr = ['John', 'Paul', 'Fred', 'Mary'];
function writeSelect(name_group) {
var my_select = document.forms[0].elements['namelist'];
// empty the list
while (my_select.options.length) my_select.options[0] = null;
// populate list with the new values
for (var i=0; i<name_group.length; ++i)
my_select.options[my_select.length]
= new Option(name_group[i], name_group[i]);
}
</script>
<title>My web page</title>
</head>
<body>
<form method="get" action="#">
<p>
<select size="1" name="namelist">
<option value="-">-</option>
</select>
<input type="button" value="Click" onClick="writeSelect(arr);">
</p>
</form>
</body>
</html>

Info about the 'Option'-object:
http://www.javascriptkit.com/jsref/s...shtml#section2

Hope this helps,

--
Bart
Jun 27 '08 #2

P: n/a
Sat, 21 Jun 2008 05:26:33 -0700 (PDT), /Bart Van der Donck/:
Info about the 'Option'-object:
http://www.javascriptkit.com/jsref/s...shtml#section2
I've always wondered how standard (official or not) is the Option
object? I mean isn't it better to use
Document.createElement("option") and the add() / remove() methods of
the HTMLSelectElement [1], or probably just Node.appendChild() /
Node.removeChild()? I've not found references to the Option object
in the "Gecko DOM Reference" [2] and the MSDN Library [3] - have I
missed them?

[1] http://www.w3.org/TR/DOM-Level-2-HTM...ml#ID-94282980
[2] http://developer.mozilla.org/en/docs..._DOM_Reference
[3] http://msdn.microsoft.com/library

--
Stanimir
Jun 27 '08 #3

P: n/a
Stanimir Stamenkov wrote:
Sat, 21 Jun 2008 05:26:33 -0700 (PDT), /Bart Van der Donck/:
>Info about the 'Option'-object:
http://www.javascriptkit.com/jsref/s...shtml#section2

I've always wondered how standard (official or not) is the Option
object?
The Option-object is one of the eldest around and was already
supported in the first j(ava)script versions.
I mean isn't it better to use Document.createElement("option")
and the add() / remove() methods of the HTMLSelectElement [1],
or probably just Node.appendChild() / Node.removeChild()? *
This belongs to a more recent coding style, which aims to advocate a
more general syntax. The benefit is that it's intended for the whole
DOM of the page, and thus technically easier for the programmer. On
the other hand, some could prefer a more classical approach too:
longer proven history, better browser support, programmer is more
confident in his old syntax, ...
I've not found references to the Option object in the "Gecko DOM
Reference" [2] and the MSDN Library [3] - have I missed them?
Yes.

--
Bart
Jun 27 '08 #4

P: n/a
Sat, 21 Jun 2008 07:51:39 -0700 (PDT), /Bart Van der Donck/:
Stanimir Stamenkov wrote:
>I've not found references to the Option object in the "Gecko DOM
Reference" [2] and the MSDN Library [3] - have I missed them?

Yes.
Could you be so kind and provide them for me? Thanks.

--
Stanimir
Jun 27 '08 #5

P: n/a
Stanimir Stamenkov wrote:
Sat, 21 Jun 2008 07:51:39 -0700 (PDT), /Bart Van der Donck/:
>Stanimir Stamenkov wrote:
>>I've not found references to the Option object in the "Gecko DOM
Reference" [2] and the MSDN Library [3] - have I missed them?
>Yes.

Could you be so kind and provide them for me? *Thanks.
http://msdn.microsoft.com/en-us/libr...77(VS.85).aspx
http://devedge-temp.mozilla.org/libr...ce/option.html

--
Bart
Jun 27 '08 #6

P: n/a
Sun, 22 Jun 2008 00:07:55 -0700 (PDT), /Bart Van der Donck/:
http://msdn.microsoft.com/en-us/libr...77(VS.85).aspx
http://devedge-temp.mozilla.org/libr...ce/option.html
Thanks. Perhaps I should have stated it more clear earlier. I was
interested where the |Option()| constructor was documented. While
the MSDN resource doesn't mention it, the older JavaScript 1.3
Reference has it. I was puzzled why the newer documentation doesn't
have it, but as Richard Cornford explained in another reply it is
pretty much because "... manufacturer documentation tends to stress
how its authors think things should be done in their own products...".

--
Stanimir
Jun 27 '08 #7

P: n/a
Bart Van der Donck wrote:
Stanimir Stamenkov wrote:
>Sat, 21 Jun 2008 05:26:33 -0700 (PDT), /Bart Van der Donck/:
>>Info about the 'Option'-object:
http://www.javascriptkit.com/jsref/s...shtml#section2
I've always wondered how standard (official or not) is the Option
object?

The Option-object is one of the eldest around and was already
supported in the first j(ava)script versions.
Evidently, while `Option' objects have been around since JavaScript 1.0,
their constructor was not available before JavaScript 1.1. The unfortunate
mix between the JavaScript core language and the Netscape Navigator DOM has
been resolved as of JavaScript 1.4. Since JavaScript 1.5 this feature and
other host objects are part of the Gecko DOM instead. (The Gecko DOM
Reference at that, is incomplete. Since it is a public Wiki since quite a
while, it can easily be made complete.)

Evidently as well, the object has never been part of JScript. However, it
is available at least since MSHTML 4.0.
PointedEars
--
Use any version of Microsoft Frontpage to create your site.
(This won't prevent people from viewing your source, but no one
will want to steal it.)
-- from <http://www.vortex-webdesign.com/help/hidesource.htm>
Jun 27 '08 #8

P: n/a
On Jun 21, 9:20 am, "LayneMitch via WebmasterKB.com" <u39402@uwe>
wrote:
Hello everyone.

I'm currently learning Javascript and doing a few exercises.

One problem I'm working on takes an array of names from an xml file using
Ajax and writes it to <select<optionstags.

This is the code they use:

function writeSelect(name_group) {
var this_option;
var my_select = document.getElementById("namelist");
for (var loop = 0; loop < name_group.length; loop++)
{
this_option = new Option();
this_option.value = the_array[loop];
this_option.text = the_array[loop]
my_select.options[loop] = this_option;
}

}

The parameter for writeSelect() function contains the array of names and the
id "namelist" is the id for the select tag in the form element.

This is my first time seeing the new Option() function. Is this the standard
for writing arrays to the <selecttag? Or could this have been done another
way - if so what this that way?

Any response would be appreciated.

--
Message posted via WebmasterKB.comhttp://www.webmasterkb.com/Uwe/Forums.aspx/javascript/200806/1
function doselect()
{
document.write("<select>");
for(var i = 0; i < array.legnth; i++)
{
document.write("<option value ="+array[i]+">"+i+"</option>");
}
document.write("</select>");
Jun 27 '08 #9

P: n/a
Baris-C wrote:
function doselect()
{
document.write("<select>");
for(var i = 0; i < array.legnth; i++)
{
document.write("<option value ="+array[i]+">"+i+"</option>");
}
document.write("</select>");
(sic!)

- Unnecessary and pointless: document.write() after load *overwrites*
- Syntactically wrong: ETAGO delimiters not escaped, missing `}'
- Typo: _length_
- Error-prone: consecutive document.write() for incomplete element
- Hopelessly inefficient: consecutive document.write(),
repeated `length' lookup (if typo was corrected)
- Bad style: uses globals unnecessarily, whitespacing and indentation sucks

Next, please.
PointedEars
--
Anyone who slaps a 'this page is best viewed with Browser X' label on
a Web page appears to be yearning for the bad old days, before the Web,
when you had very little chance of reading a document written on another
computer, another word processor, or another network. -- Tim Berners-Lee
Jun 27 '08 #10

P: n/a
<script language="javascript">

doselect();

function doselect()
{
try
{
var array = Array("select your value","bir","su
bende","yine","cennet","zor gzel","A","yok","insanlar","sus","sakn
syleme","ben","ala","g");

document.write("<select>");
for(var i = 0; i < array.length; i++)
{
document.write("<option value ="+i+">"+array[i]+"</option>");
}

document.write("</select>");
}

catch(e)
{
document.write(e.name+" : "+e.description);
}
}
</script>
Jun 27 '08 #11

P: n/a
Baris-C wrote:
<script language="javascript">
<http://validator.w3.org/#validate-by-input>
doselect();

function doselect()
This is still unnecessary and pointless. If would only make sense if the
Array object reference would be passed instead, so that the method would
become general.
{
try
{
Unnecessary. Error-prone, because not universally supported. No statement
here is going to throw an exception.
var array = Array("select your value","bir","suç
^^^^^
Unwise choice for an identifier.
bende","yine","cennet","zor güzel","A","yok","insanlar","sus","sakın
söyleme","ben","ağla","göç");
This should be passed as an argument (in the following: `a') instead.
document.write("<select>");
for(var i = 0; i < array.length; i++)
{
document.write("<option value ="+i+">"+array[i]+"</option>");
}

document.write("</select>");
}
Sigh. [psf 10.1]

function esc(s)
{
return String(s).replace(
/[<>&]/g,
function(m) { return "&#" + m.charCodeAt(0) + ";" });
}

var out = ['<select size="1">'];

for (var i = 0, len = a.length; i < len; i++)
{
// if Array.prototype.push() isn't available,
// augmentation needs to provide it
out.push('<option value="' + i + '"' + (i === 0 ? ' selected' : '')
+ '>' + esc(a[i]) + '<\/option>');
}

out.push('<\/select>');

// "\n" for pretty printing
document.write(out.join("\n"));
catch(e)
{
document.write(e.name+" : "+e.description);
}
If document.write() throws an exception (which is the only statement that
could be expected to, in Gecko's XHTML DOM), what makes you think that
another document.write() call could be successful then? Even more, what
makes you think this message could be helpful to the user?
PointedEars
--
var bugRiddenCrashPronePieceOfJunk = (
navigator.userAgent.indexOf('MSIE 5') != -1
&& navigator.userAgent.indexOf('Mac') != -1
) // Plone, register_function.js:16
Jun 27 '08 #12

P: n/a
Tue, 24 Jun 2008 03:51:33 -0700 (PDT), /Baris-C/:
document.write("<select>");
for(var i = 0; i < array.length; i++)
{
document.write("<option value ="+i+">"+array[i]+"</option>");
}
document.write("</select>");
Thomas Lahn already pointed in another reply invoking
document.write() after load overwrites the document but
document.write() also doesn't work with XHTML documents:

http://www.w3.org/MarkUp/2004/xhtml-faq#docwrite

--
Stanimir
Jun 27 '08 #13

This discussion thread is closed

Replies have been disabled for this discussion.