473,654 Members | 3,253 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Adding OPTION tags dynamically

Can anyone give me a quick code snippet (that is standards-based) for adding
OPTION tags to a SELECT dynamically. I have no problem doing it in IE but I
am kind of new to the whole standards world and can't figure out how to make
it work in, for instance, Firefox. Right now the code I am using is as
follows:

newOpt=document .createElement( 'OPTION');
newOpt.id='optK eyword';
newOpt.label='K eyword';
document.getEle mentById('slctC ategory').add(n ewOpt);

This code won't work in IE OR Firefox since neither of them operate
according to the standard defined in HTML 4.01 where the label property
should be used as the option contents if it is set. If I change it from
setting the label property to setting the text property, it works in IE, but
not in Firefox. According to HTML 4.01 the text property is supposed to be
read only, thus I would expect that's the reason it doesn't work in Firefox.
Anyways, some help on this would be appreciated!

David
Jul 23 '05 #1
10 4866
In response to my previous post, I have discovered that I CAN set the text
property in Firefox as well and it works (though I still recall reading that
it is supposed to be a readonly property). Anyways, now my problem is the
following line:

document.getEle mentById('slctC ategory').add(n ewOpt);

If I use this line in IE, it works fine, but it won't work like this in
Firefox, as it expects a final argument, so if I put it like this it works:

document.getEle mentById('slctC ategory').add(n ewOpt,null);

I have NO idea why on earth it should expect that final argument,
particularly when it has to be null, but Firefox will not add the new option
otherwise. Anyways, I could obviously use my global "isIE" variable to make
the code branch here but that is something I am trying to avoid. Is there a
different way of going about this all which would be better?
"David" <dk****@hotmail .com> wrote in message
news:h8******** ************@co mcast.com...
Can anyone give me a quick code snippet (that is standards-based) for
adding OPTION tags to a SELECT dynamically. I have no problem doing it in
IE but I am kind of new to the whole standards world and can't figure out
how to make it work in, for instance, Firefox. Right now the code I am
using is as follows:

newOpt=document .createElement( 'OPTION');
newOpt.id='optK eyword';
newOpt.label='K eyword';
document.getEle mentById('slctC ategory').add(n ewOpt);

This code won't work in IE OR Firefox since neither of them operate
according to the standard defined in HTML 4.01 where the label property
should be used as the option contents if it is set. If I change it from
setting the label property to setting the text property, it works in IE,
but not in Firefox. According to HTML 4.01 the text property is supposed
to be read only, thus I would expect that's the reason it doesn't work in
Firefox. Anyways, some help on this would be appreciated!

David

Jul 23 '05 #2
David wrote:
In response to my previous post, I have discovered that I CAN set the text
property in Firefox as well and it works (though I still recall reading that
it is supposed to be a readonly property). Anyways, now my problem is the
following line:

document.getEle mentById('slctC ategory').add(n ewOpt);

If I use this line in IE, it works fine, but it won't work like this in
Firefox, as it expects a final argument, so if I put it like this it works:

document.getEle mentById('slctC ategory').add(n ewOpt,null);

I have NO idea why on earth it should expect that final argument,
particularly when it has to be null, but Firefox will not add the new option
otherwise. Anyways, I could obviously use my global "isIE" variable to make
the code branch here but that is something I am trying to avoid. Is there a
different way of going about this all which would be better?
"David" <dk****@hotmail .com> wrote in message
news:h8******** ************@co mcast.com...
Can anyone give me a quick code snippet (that is standards-based) for
adding OPTION tags to a SELECT dynamically. I have no problem doing it in
IE but I am kind of new to the whole standards world and can't figure out
how to make it work in, for instance, Firefox. Right now the code I am
using is as follows:

newOpt=document .createElement( 'OPTION');
newOpt.id='optK eyword';
If you are adding multiple options, ensure the IDs are unique.
newOpt.label='K eyword';
Option elements do not have a 'label' property. Label elements can
contain form controls, but an option element is not a form control, it's
the child of a select (which is a form control). At least that is my
reading of the spec.
document.getEle mentById('slctC ategory').add(n ewOpt);


The following should suit:

var txt = 'Keyword';
var val = 'Some value';
var newOpt = new Option( txt, val, false, true );
myList.options[myList.options. length] = newOpt;

'txt' is the option text, 'val' the option value and 'false' modifies
the option's selected attribute (true would make the option selected).
The first two parameters are required, the rest can usually be omitted
but it's probably good practice to include them.

I'm not sure it's 100% 'DOM compliant', but the real test is whether it
works reliably in the great majority of browsers without undue
side-effects - I think it meets those criteria.

There is a thread here that may help:

<URL:http://groups-beta.google.com/group/comp.lang.javas cript/browse_frm/thread/af6e808b089f60f 8/0a5222cd15fc5e1 1?q=add+option+ select+drop+dow n+IE&rnum=3&hl= en#0a5222cd15fc 5e11>

[...]
--
Rob
Jul 23 '05 #3
RobG wrote:
[...]

The following should suit:

var txt = 'Keyword';
var val = 'Some value';
var newOpt = new Option( txt, val, false, true );
myList.options[myList.options. length] = newOpt;

'txt' is the option text, 'val' the option value and 'false' modifies
the option's selected attribute (true would make the option selected).
The first two parameters are required, the rest can usually be omitted
but it's probably good practice to include them.


Forgot to add that the last parameter (set to 'true' above) sets whether
the option is the currently selected option.

--
Rob
Jul 23 '05 #4
David wrote:
In response to my previous post, I have discovered that I CAN set the
text property in Firefox as well and it works (though I still recall
reading that it is supposed to be a readonly property). Anyways, now
my problem is the following line:

document.getEle mentById('slctC ategory').add(n ewOpt);

If I use this line in IE, it works fine, but it won't work like this
in Firefox, as it expects a final argument, so if I put it like this
it works:
document.getEle mentById('slctC ategory').add(n ewOpt,null);

I have NO idea why on earth it should expect that final argument,
particularly when it has to be null, but Firefox will not add the new
option otherwise. Anyways, I could obviously use my global "isIE"
variable to make the code branch here but that is something I am
trying to avoid. Is there a different way of going about this all
which would be better?

"David" <dk****@hotmail .com> wrote in message
news:h8******** ************@co mcast.com...
Can anyone give me a quick code snippet (that is standards-based) for
adding OPTION tags to a SELECT dynamically. I have no problem doing
it in IE but I am kind of new to the whole standards world and can't
figure out how to make it work in, for instance, Firefox. Right now
the code I am using is as follows:

newOpt=document .createElement( 'OPTION');
newOpt.id='optK eyword';
newOpt.label='K eyword';
document.getEle mentById('slctC ategory').add(n ewOpt);

This code won't work in IE OR Firefox since neither of them operate
according to the standard defined in HTML 4.01 where the label
property should be used as the option contents if it is set. If I
change it from setting the label property to setting the text
property, it works in IE, but not in Firefox. According to HTML
4.01 the text property is supposed to be read only, thus I would
expect that's the reason it doesn't work in Firefox. Anyways, some
help on this would be appreciated! David


Try

document.getEle mentById('slctC ategory').appen dChild(newOpt);

instead.

--
Stan
Jul 23 '05 #5
Thanks to those who helped out, both suggestions worked. Funnily enough, I
knew about, but had ruled out, the newOpt = new Option(....) method because
I believed it to be IE-specific, but I guess I was wrong there. Anyhow, I'm
sure I'll have lots more questions to come as my project goes on.

Thanks again,

David
Jul 23 '05 #6
ASM
David wrote:
the newOpt = new Option(....) method because
I believed it to be IE-specific


not at all !
it is a very old Javascript way of doing
stil in use ;-)
--
Stephane Moriaux et son [moins] vieux Mac
Jul 23 '05 #7
"David" <dk****@hotmail .com> wrote:
Can anyone give me a quick code snippet (that is standards-based) for
adding OPTION tags to a SELECT dynamically. I have no problem doing it
in IE but I am kind of new to the whole standards world and can't figure
out how to make it work in, for instance, Firefox. Right now the code I
am using is as follows:

newOpt=document .createElement( 'OPTION');
newOpt.id='optK eyword';
newOpt.label='K eyword';
document.getEle mentById('slctC ategory').add(n ewOpt);


The code I got was from <http://www.mredkj.com/tutorials/tutorial005.htm l>
and it explained what to use and why....here's my slight tweaking of it to
make it more general:

function addOption(elSel ,newText,newVal ue, elOptOld) {
// have to call createElement for EACH new option
var elOptNew = document.create Element('option ');
var newIndex;

elOptNew.text = newText;
elOptNew.value = newValue;

try { // standards compliant method; doesn't work in IE
elSel.add(elOpt New, elOptOld);
} catch(ex) {
if (elOptOld != null) {
newIndex = elOptOld.index+ 1
} else {
newIndex = elSel.length +1
}
elSel.add(elOpt Newm, newIndex); // IE only
}
}

But I have my own problem, related to this (as I just posted in a different
group)...

I'm using one menu to populate another (i.e. teams/players cars/makes that
kind of thing), and I'd like to be able to hide the 2nd menu, and it's
label when the menu is empty.

Hiding the menu is no problem, but I don't know how to find the menu's
label. Any suggestions (other than givign the label an ID, I know that
would work, but would prefer something a more general).

--
J.B.Moreno
Jul 23 '05 #8
"J. B. Moreno" <pl***@newsread ers.com> wrote in message
news:20******** ***********@new sreader.com...
"David" <dk****@hotmail .com> wrote:
Can anyone give me a quick code snippet (that is standards-based) for
adding OPTION tags to a SELECT dynamically. I have no problem doing it
in IE but I am kind of new to the whole standards world and can't figure
out how to make it work in, for instance, Firefox. Right now the code I
am using is as follows:

newOpt=document .createElement( 'OPTION');
newOpt.id='optK eyword';
newOpt.label='K eyword';
document.getEle mentById('slctC ategory').add(n ewOpt);


The code I got was from <http://www.mredkj.com/tutorials/tutorial005.htm l>
and it explained what to use and why....here's my slight tweaking of it to
make it more general:

function addOption(elSel ,newText,newVal ue, elOptOld) {
// have to call createElement for EACH new option
var elOptNew = document.create Element('option ');
var newIndex;

elOptNew.text = newText;
elOptNew.value = newValue;

try { // standards compliant method; doesn't work in IE
elSel.add(elOpt New, elOptOld);
} catch(ex) {
if (elOptOld != null) {
newIndex = elOptOld.index+ 1
} else {
newIndex = elSel.length +1
}
elSel.add(elOpt Newm, newIndex); // IE only
}
}

But I have my own problem, related to this (as I just posted in a
different
group)...

I'm using one menu to populate another (i.e. teams/players cars/makes that
kind of thing), and I'd like to be able to hide the 2nd menu, and it's
label when the menu is empty.

Hiding the menu is no problem, but I don't know how to find the menu's
label. Any suggestions (other than givign the label an ID, I know that
would work, but would prefer something a more general).

--
J.B.Moreno


In regards to your question about finding the label, I really don't know the
exact situation but is it possible to use parentNode, childNodes, or
nextSibling properties/collections to access the label relative to each
menu? Also might try using getElementsByTa gName on the parent element of
the menu/label to get a collection of all elements with the label's tag name
within the parent. Then you can use the returned collection and choose the
index within the collection which is the label element. Kinda hard to be
very specific without a look at the HTML structure you are using but I hope
maybe one of these might get you started in the right direction.
Jul 23 '05 #9
"David" <dk****@hotmail .com> wrote:
"J. B. Moreno" <pl***@newsread ers.com> wrote in message -snip-
I'm using one menu to populate another (i.e. teams/players cars/makes
that kind of thing), and I'd like to be able to hide the 2nd menu, and
it's label when the menu is empty.


-snip-
In regards to your question about finding the label, I really don't know
the exact situation but is it possible to use parentNode, childNodes, or
nextSibling properties/collections to access the label relative to each
menu?
Pretty much my question exactly!
Also might try using getElementsByTa gName on the parent element of
the menu/label to get a collection of all elements with the label's tag
name within the parent. Then you can use the returned collection and
choose the index within the collection which is the label element. Kinda
hard to be very specific without a look at the HTML structure you are
using but I hope maybe one of these might get you started in the right
direction.


I would like to assume the minimal structure possible....

<form action="somethi ng" method="post">
<label for="team">
Teams:
<select name="team" id="team">
<option>Great </option>
</select>
</label>
</form>

--
J.B.Moreno
Jul 23 '05 #10

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

Similar topics

3
3149
by: daveland | last post by:
I am working on some JavaScript that dynamically adds rows to a table in response to a button click. A new row does appear on the screen when the button is clicked. However, that table to which a row has been added is itself contained within an outer table (to handle the desired screen layout). That outer table does not properly grow to contain the new size of the table to which the row was added. (More specifically, I have...
3
15610
by: Stewart | last post by:
Dear comp.lang.javascript, I have more than once wanted to manipulate the contents of select boxes dynamically, whilst the boxes contain <optgroup> tags. Manipulation of a select box containing only <option> tags is fairly easy and there is plenty of material on the net to assist with this. However, I have searched long and found the material on the subject of <optgroup> to be sparse, with a few posts here & there, but basically you're...
20
12879
by: David | last post by:
I have a one-line script to add an onunload event handler to the body of the document. The script is as follows: document.getElementsByTagName("BODY").onunload=function s() {alert("s")} Now obviously, I put the alert("s") part in for debugging purposes, just to make sure the error wasn't in any code I was going to be running. This line works just fine in IE6 but in Firefox it doesn't. However, if I replace that line with the...
9
39761
by: Michelle | last post by:
I have a div that is initially empty. Clicking on a button will add some text boxes and other controls so the user can add additional records. In IE all works fine but in Netscape 7.0 when I add another "record" the values for all previous controls within the div are wiped out. In the javascript function where I add on to the html in the div if I capture all the data in the previous "records" then after adding the new record I can...
7
2040
by: | last post by:
What is the beat way to dynamically write/add to the HEAD tag of an ASPX page (the <head runat=server ... is too error prone and not very repeatable)? Thanks.
0
1871
by: Sileesh | last post by:
Hi I have html table and a Button in an Aspx page. I am adding one row with some textboxes to Html table each time i click on the Button thru Javascript. Now problem is when when i try to collect the data in the Textboxes which i added dynamically from server side, i am not able to do . Alos i tried to bedug, the total no of rows in Html table does not reflect the dynamically added rows.
6
436
by: Nathan Sokalski | last post by:
I am trying to dynamically add controls to my page, but am having trouble with controls such as buttons. I have been able to add simple controls such as Label controls, because they can be placed anywhere. I have managed to add Labels using the following code: Dim extralabel As Label = New Label extralabel.Text = "Generated Label" Me.Controls.Add(extralabel)
6
19593
by: joseph.lindley | last post by:
Forgive me for I am a bit of a web-dev novice - but I'm not doing too bad. I'm currently working with a bit of javascript to dynamically add <option>s into a select box. My code currently works fine in Internet Explorer, however in Firefox the dropdown only displays the first option in the list, and when clicked the other values aren't displayed. Here is the code;
1
1844
by: CapRand | last post by:
Hi, I am creating an ASP.NET site and have created a form which I have been able to dynamically with listboxes, labels etc from a database - using mainly form1.Controls.Add ..... Does anyone know how I can add blank lines to a form. If I use response.write it writes to the body of the HTML and not inside the form. I am sure it must be easy but it has got me stuck. I have tried adding a label with vbcrlf inside it but the CRLF stays...
0
8379
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
8294
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
8816
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
8709
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
8494
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
7309
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5627
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2719
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
1597
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.