473,714 Members | 2,552 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

drop down error

hello,
Question, on page load, I populate an existing drop down with
createElement and appendChild. It works fine so far. BUT I want to
automatically select some option from this populated drop down. So i
have this statement:

document.getEle mentById("dropd own").options[someindex].selected=true;

And it gives me an error.

Surprisingly, when i put an alert statement before appending the
created element to dropdown, the error doesn't occur.
Can anyone help please?

Thanks

Jul 23 '05 #1
7 5882
debugger wrote:
hello,
Question, on page load, I populate an existing drop down with
createElement and appendChild. It works fine so far. BUT I want to
automatically select some option from this populated drop down. So i
have this statement:

document.getEle mentById("dropd own").options[someindex].selected=true;

And it gives me an error.
What is the error message?
Surprisingly, when i put an alert statement before appending the
created element to dropdown, the error doesn't occur.
That indicates a timing issue.
Can anyone help please?


Start with the group FAQ

--
Randy
comp.lang.javas cript FAQ - http://jibbering.com/faq
Jul 23 '05 #2
debugger wrote:
hello,
Question, on page load, I populate an existing drop down with
createElement and appendChild. It works fine so far. BUT I want to
automatically select some option from this populated drop down. So i
have this statement:

document.getEle mentById("dropd own").options[someindex].selected=true;

And it gives me an error.

Surprisingly, when i put an alert statement before appending the
created element to dropdown, the error doesn't occur.
Can anyone help please?


Probably the browser is still creating the option when you try
to grab it with getElementById. Putting in the alert gives the
browser time to create it.

Why not set the selected attribute when you create the option?

...
var oOpt = document.create Element('option ');
oOpt.selected = true;
...

Then you don't need to use gEBI.
--
Rob
Jul 23 '05 #3
In article <11************ **********@c13g 2000cwb.googleg roups.com>,
js********@yaho o.com enlightened us with...
Question, on page load, I populate an existing drop down with
createElement and appendChild. It works fine so far. BUT I want to
automatically select some option from this populated drop down. So i
have this statement:

document.getEle mentById("dropd own").options[someindex].selected=true;

And it gives me an error.
Magic 8 ball failed.
What's the error?

Surprisingly, when i put an alert statement before appending the
created element to dropdown, the error doesn't occur.
Can anyone help please?


Not without seeing actual code, no.
But more than likely, you're trying to access something that hasn't been
fully created/rendered yet.

--
--
~kaeli~
A little rudeness and disrespect can elevate a meaningless
interaction to a battle of wills and add drama to an
otherwise dull day.
http://www.ipwebdesign.net/wildAtHeart
http://www.ipwebdesign.net/kaelisSpace

Jul 23 '05 #4
the error is "htmlfile: Could not set the selected property.
Unspecified error."

option element for drop down is created by:
for(.......)
{
var myEle = document.create Element("option ");
myEle.value=som e value;
myEle.innerHTML = some string;
document.getEle mentById("someD ropDown").appen dChild(myEle);
}
after this, there is other for loop setting the selected property.
code causing the error:
for(var k=0; k<something; k++)
{
if(somecodition )
{
var mySelectedOptio n =
document.getEle mentById("someD ropDown").optio ns[k];
mySelectedOptio n.selected=true ; <<<<<<<<<<<<=== ===== error
occurs here
}
}

now when i put alert in the above "if statement", the error does not
occur.
Folks have already pointed out its a timing issue, thanks for that. But
I m not sure how to solve it.
thanks again.

Jul 23 '05 #5
debugger wrote:
the error is "htmlfile: Could not set the selected property.
Unspecified error."

option element for drop down is created by:
for(.......)
{
var myEle = document.create Element("option ");
myEle.value=som e value;
myEle.innerHTML = some string;
Yuck. Why use innerHTML?

myEle.appendChi ld(document.cre ateTextNode('so me string'));
document.getEle mentById("someD ropDown").appen dChild(myEle);
Do some feature detection before using gEBI (and you should
probably include a document.all method too if using gEBI):

if (document.getEl ementById) {
document.getEle mentById("someD ropDown")...;
...

Or even better, use the forms collection:

document.forms['someDropDown']...;

Avoids gEBI entirely - but see notes below.
}
after this, there is other for loop setting the selected property.
code causing the error:
for(var k=0; k<something; k++)
{
if(somecodition )
{
var mySelectedOptio n =
document.getEle mentById("someD ropDown").optio ns[k];
mySelectedOptio n.selected=true ; <<<<<<<<<<<<=== ===== error
occurs here
Why not keep a reference to "someDropDo wn" when you access it
above, then use it again when referencing the option:

var myDropDown = document.forms['someDropDown'];
myDropDown.appe ndChild(myEle);

...

myDropDown.opti ons[k].selected = true;
Now there is no need for the second gEBI (or if the forms
collection is used, no need for gEBI at all)

[...] now when i put alert in the above "if statement", the error does not
occur.


Whilst Firefox does not generate an error, IE does. The error
is not fatal and the script appears to execute properly - the
option is added and selected. If users have not set IE to
report JavaScript errors, they will not see any error and the
script works fine. I would call this a bug in IE.

You can use setAttribute to keep IE happy, but then Firefox will
not select the option. Given that browser detection should only
be used as an absolute last resort, this would seem an
appropriate place to use try/catch:

if ( i == len-1){
try {
mySel.options[i].selected = true;
} catch(e) {
mySel.options[i].setAttribute(' selected', true);
}
}

In future, please post code that actually replicates the error,
it makes the job of suggesting fixes much easier.

The following code implements the suggestions above and fixes
the error.

I still don't understand why you don't set myEle (the option) to
selected when you create it, that way works in both Firefox and
IE without the try/catch nastiness.
<html><head><ti tle>play</title>
</head><body>
<script type="text/javascript">
function doStuff() {
var mySel = document.forms['aForm'].elements['someDropDown'];
var myEle = document.create Element('option ');
myEle.value= 'someValue';
myEle.appendChi ld(document.cre ateTextNode('so me string'));

// why not set it to selected here?
// myEle.selected = true;

mySel.appendChi ld(myEle);

// if set to selected above, this whole block is not needed.
var len = mySel.length;
for (var i=0; i<len; i++) {
if ( i == len-1){
try {
mySel.options[i].selected = true;
} catch(e) {
mySel.options[i].setAttribute(' selected', true);
}
}
}

}

</script>
</head><body>

<form action="" name="aForm">
<select name="someDropD own" id="someDropDow n">
<option value="steve">S teve</option>
<option value="harry">H arry</option>
<option value="sue">Sue </option>
</select>
<br>
<input type="button" onclick="doStuf f();" value="Click">
</form>

</body></html>

--
Rob
Jul 23 '05 #6
Thank alot Rob,

Your try and catch did the job. I didn't know about the
document.create TextNode() earlier. And thanks for pointing that out.
For your question:
// why not set it to selected here?
// myEle.selected = true;
I have three for loops and in the third for loop, i have an if
conditional to check for which item to select(as there are many to
select from). Now for others to understand my code, I have the "if"
conditional in separate for loop. Therefore I did that just for
readability purposes. I think are right, I should put it after element
is created.

Thanks again,
JS
RobG wrote: debugger wrote:
the error is "htmlfile: Could not set the selected property.
Unspecified error."

option element for drop down is created by:
for(.......)
{
var myEle = document.create Element("option ");
myEle.value=som e value;
myEle.innerHTML = some string;


Yuck. Why use innerHTML?

myEle.appendChi ld(document.cre ateTextNode('so me string'));
document.getEle mentById("someD ropDown").appen dChild(myEle);


Do some feature detection before using gEBI (and you should
probably include a document.all method too if using gEBI):

if (document.getEl ementById) {
document.getEle mentById("someD ropDown")...;
...

Or even better, use the forms collection:

document.forms['someDropDown']...;

Avoids gEBI entirely - but see notes below.
}
after this, there is other for loop setting the selected property.
code causing the error:
for(var k=0; k<something; k++)
{
if(somecodition )
{
var mySelectedOptio n =
document.getEle mentById("someD ropDown").optio ns[k];
mySelectedOptio n.selected=true ; <<<<<<<<<<<<=== ===== error
occurs here


Why not keep a reference to "someDropDo wn" when you access it
above, then use it again when referencing the option:

var myDropDown = document.forms['someDropDown'];
myDropDown.appe ndChild(myEle);

...

myDropDown.opti ons[k].selected = true;
Now there is no need for the second gEBI (or if the forms
collection is used, no need for gEBI at all)

[...]
now when i put alert in the above "if statement", the error does not occur.


Whilst Firefox does not generate an error, IE does. The error
is not fatal and the script appears to execute properly - the
option is added and selected. If users have not set IE to
report JavaScript errors, they will not see any error and the
script works fine. I would call this a bug in IE.

You can use setAttribute to keep IE happy, but then Firefox will
not select the option. Given that browser detection should only
be used as an absolute last resort, this would seem an
appropriate place to use try/catch:

if ( i == len-1){
try {
mySel.options[i].selected = true;
} catch(e) {
mySel.options[i].setAttribute(' selected', true);
}
}

In future, please post code that actually replicates the error,
it makes the job of suggesting fixes much easier.

The following code implements the suggestions above and fixes
the error.

I still don't understand why you don't set myEle (the option) to
selected when you create it, that way works in both Firefox and
IE without the try/catch nastiness.
<html><head><ti tle>play</title>
</head><body>
<script type="text/javascript">
function doStuff() {
var mySel = document.forms['aForm'].elements['someDropDown'];
var myEle = document.create Element('option ');
myEle.value= 'someValue';
myEle.appendChi ld(document.cre ateTextNode('so me string'));

// why not set it to selected here?
// myEle.selected = true;

mySel.appendChi ld(myEle);

// if set to selected above, this whole block is not needed.
var len = mySel.length;
for (var i=0; i<len; i++) {
if ( i == len-1){
try {
mySel.options[i].selected = true;
} catch(e) {
mySel.options[i].setAttribute(' selected', true);
}
}
}

}

</script>
</head><body>

<form action="" name="aForm">
<select name="someDropD own" id="someDropDow n">
<option value="steve">S teve</option>
<option value="harry">H arry</option>
<option value="sue">Sue </option>
</select>
<br>
<input type="button" onclick="doStuf f();" value="Click">
</form>

</body></html>

--
Rob


Jul 23 '05 #7
debugger wrote:
Thank alot Rob,

Your try and catch did the job. I didn't know about the
document.create TextNode() earlier. And thanks for pointing that out.
For your question:
// why not set it to selected here?
// myEle.selected = true;

I have three for loops and in the third for loop, i have an if
conditional to check for which item to select(as there are many to
select from). Now for others to understand my code, I have the "if"
conditional in separate for loop. Therefore I did that just for
readability purposes. I think are right, I should put it after element
is created.

Thanks again,


Glad to help. :-)

--
Rob
Jul 23 '05 #8

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

Similar topics

4
6312
by: Dan | last post by:
Can anyone offer suggestions on how to do this or if it is possible? I have a form that uses a drop down box and 2 text fields. What I am trying to do is have the value of each text box set by the choice from the drop down box. Something like: <form name="populatefrm" id="contactfrm" method="post"
1
2913
by: Dan | last post by:
This is one that has me stumped and I need an expert's input. Any ideas why the values from the second script-generated drop down list isn't recognized by the script to add time values to the text boxes? What this script is suppose to do is change the value of a second drop down list based on the selection from the first. Then a value is chosen from the script generated drop down list in the
4
1678
by: rajat | last post by:
Hi, I have adapted a drop down menu from USC webpage (www.usc.edu). The link to my page is http://www-scf.usc.edu/~swarup/test/test.html The links to the CSS ans JS files are: http://www-scf.usc.edu/~swarup/test/Templates/dropdown.css http://www-scf.usc.edu/~swarup/test/Templates/default.js The problem I'm facing is that in IE 6 when the mouse gets over the drop down menu it does not display sometimes (and sometimes it does).
3
14220
by: Miguel Dias Moura | last post by:
Hello, i have an ASP.NET / VB page where i have a few 4 groups of Drop Down Lists. Each group of Drop Down Lists include 3 Drop Down Lists for date such as: DAY, MONTH, and YEAR. I don't want to insert the values and text to each drop down list. So i want to create a script that populates a certain Drop Down List with certain values when page loads such as:
5
4228
by: Vigneshwar Pilli via DotNetMonster.com | last post by:
string connectionString1 = "server=(local); user=sa;password=sa; database=sonic"; System.Data.SqlClient.SqlConnection dbConnection1 = new System.Data.SqlClient.SqlConnection(connectionString1); System.Data.SqlClient.SqlCommand dbCommand1 = new System.Data.SqlClient.SqlCommand();
6
2025
by: Joey Liang via DotNetMonster.com | last post by:
Hi all, I have a drop down list which store all the different brands of product.When i selected the particular brand from the drop down list, it will display all the products with the selected brand in a datagrid. I have this error when i select a brand from the drop down list. Blow is my code,anyone can help me to solve my error,which part of my code went wrong? Really thanx and very appreciate your help in advanced.. I have been stucked...
6
2237
by: John | last post by:
I have a drop down on my form and I need all the values in that drop down and pass to a stored procedure, how can I get the values of the drop down and pass them all to my stored procedure call?
6
2364
by: zacks | last post by:
I have an application I am developing that has a Combo Box that is intended to show a list of available tables in the selected DSN. I have put code in the control's DropDown event handler to clear the item list and reload it from the currently specified DSN (in a Text Box control on the same form). This works well. BUT ... if the specified DSN is invalid, I can display an appropriate error message, but then then empty dropdown list is...
0
2355
by: yosri2005 | last post by:
Hello, I'm sure many of you have seen the error message in the subject. I found quiet a few posts on the web regarding this issue, but the ones I saw mainly tackle this issue when you have a drop-down list depending on another drop-down list within a form view. This is not what I'm trying to do, so I didn't know how to apply the solutions I found to my problem. I have a formview which inserts items into a database table via an
0
8801
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
8707
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
9314
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
9174
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
9074
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,...
1
6634
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5947
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();...
0
4464
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
3158
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

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.