473,387 Members | 1,516 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Writing Arrays To <select> Tag

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
12 2293
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
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
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
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
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
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
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
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
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
<script language="javascript">

doselect();

function doselect()
{
try
{
var array = Array("select your value","bir","suç
bende","yine","cennet","zor güzel","A","yok","insanlar","sus","sakýn
söyleme","ben","aðla","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
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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Andrea | last post by:
Hi, I'm trying to emulate part of our client-server application as a web site so customers can use it, and I'm stuck when it comes to re-ordering items in a list. Basically we have a list of...
1
by: Ang Talunin | last post by:
Hey, I wondering if it's possible to retrieve all the <option>-fields from a <select> when posting a <form> to a php file Example: I've got a form like this: <form action = phpfile.php...
6
by: Bonge Boo! | last post by:
This has got to be obvious, but I can't make it work. I have a form called with 3 pull down menus. They are linked to a database which generates the values for the <SELECT? Pull-downs. Lets...
4
by: joiv | last post by:
I'm making a <select></select> with lots of <option></option>. It contains all possible options. Because of the length of the list, I also have an <input type="text">. This is what I wish to do:...
5
by: Brian Foley | last post by:
Hello, I am used to using the label tag with check boxes and radio buttons in html forms. This allows me to click on the text of the label to activate/deactivate the check box / button, rather...
0
by: rayone | last post by:
Hi folks. I need advice. 2 options, which do you think is the better option to display/retrieve/report on the data. Keep in mind reporting (Crystal), SQL Performance, VB Code, usability,...
6
by: Chris Fink | last post by:
Does anyone know it is possible to include a small image(.gif .jpeg) within a <SELECT><option> so that the user would see the option text as well as a little image(icon) in the option? I know this...
4
by: luftikus143 | last post by:
Hi there, I have a nasty little problem, as so often, only with IE. Here is an screenshot to better illustrate the problem. http://geodata.grid.unep.ch/screenshot13.png The map is clickable (to...
4
by: Man-wai Chang | last post by:
-- iTech Consulting Co., Ltd. Expert of ePOS solutions Website: http://www.itech.com.hk (IE only) Tel: (852)2325 3883 Fax: (852)2325 8288
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
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
0
BarryA
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...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
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...
0
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...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.