473,766 Members | 2,172 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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<options tags.

This is the code they use:

function writeSelect(nam e_group) {
var this_option;
var my_select = document.getEle mentById("namel ist");
for (var loop = 0; loop < name_group.leng th; loop++)
{
this_option = new Option();
this_option.val ue = the_array[loop];
this_option.tex t = the_array[loop]
my_select.optio ns[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 2333
LayneMitch wrote:
One problem I'm working on takes an array of names from an xml file using
Ajax and writes it to <select<options tags.

This is the code they use:

function writeSelect(nam e_group) {
* *var this_option;
* *var my_select = document.getEle mentById("namel ist");
* *for (var loop = 0; loop < name_group.leng th; loop++)
* * * {
* * * * this_option = new Option();
* * * * this_option.val ue = the_array[loop];
* * * * this_option.tex t = the_array[loop]
* * * * my_select.optio ns[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.getEl ementById("name list")'.
- 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(nam e_group) {
var my_select = document.forms[0].elements['namelist'];
// empty the list
while (my_select.opti ons.length) my_select.optio ns[0] = null;
// populate list with the new values
for (var i=0; i<name_group.le ngth; ++i)
my_select.optio ns[my_select.lengt h]
= new Option(name_gro up[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="writeS elect(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.create Element("option ") and the add() / remove() methods of
the HTMLSelectEleme nt [1], or probably just Node.appendChil d() /
Node.removeChil d()? 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.create Element("option ")
and the add() / remove() methods of the HTMLSelectEleme nt [1],
or probably just Node.appendChil d() / Node.removeChil d()? *
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<options tags.

This is the code they use:

function writeSelect(nam e_group) {
var this_option;
var my_select = document.getEle mentById("namel ist");
for (var loop = 0; loop < name_group.leng th; loop++)
{
this_option = new Option();
this_option.val ue = the_array[loop];
this_option.tex t = the_array[loop]
my_select.optio ns[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/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

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
3823
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 available articles ("availableItems") and a list of articles already in an issue ("selectedItems"). What I want is to be able to move articles freely between the two lists and then on submission add them to the issue (which I can), but also move...
1
2417
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 method=post > <select name= "name">
6
2408
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 say I have values selected for all three pull down menus. When I change the first "top-level" menu I want to reset both the second and third menus to the "default" state.
4
2141
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: onKeyDown I want all options that don't contain (or begin with, it doesn't matter which one) the typed letters to be removed from the <select>. My problem is that I don't know of any code to find words and identify
5
8319
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 than having to click on the (possibly small) box or button. I recently tried to assign a label to a select "drop down list", but found that when I clicked on the label text to bring it into focus, the select box was reset to the first entry. ...
0
2233
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, architecture. Case 1: On a web page I would like to render a dropdown list
6
13024
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 is not an ASP.NET related question, but I know this group is knowledgeable and quick with responses. Thanks
4
3590
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 enable zoom in and other functions). But in this case, I would like to select a value from the drop-down list, which displays as a "drop-up" list because of not having enough space downwards. Now, when I click to select a year, IE interprets this...
4
39411
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
9571
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9404
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10168
Oralloy
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10009
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9959
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
5279
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3929
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3532
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2806
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.