473,898 Members | 3,458 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

getElementsByNa me undefined for dynamic elements (radio buttons)

I have a set of radio buttons that are created dynamically, after
rendered I try loop thru this set by getting the length of the set, but
I keep getting an error stating the element is undefined. I am using
getElelementsBy Name since these are radio buttons, but it seems that
the dynamic element is not seen!!!

This is my code... please let me know if there is anything that I am
doing wrong! - thanks
----
....
....
// this loops thru an ajax structure --- this is correct so I kow is
not an Ajax issue.

for(var i=0; i<ds.Tables[0].Rows.length; i++){
//creating nue input element
var r=document.crea teElement('<INP UT type=radio name=company >');
r.type="radio";
r.name ="company";
r.id ="myradiobutton " + i;
r.setAttribute( "value",ds.Tabl es[0].Rows[i].roottype);
td_company.appe ndChild(r);
td_company.appe ndChild(documen t.createTextNod e(ds.Tables[0].Rows[i].roottypedesc)) ;
}

-----
My function trying to get the lenght of the set is called after the
radion buttons are rendered. If I find one that has an specific value,
I check it.

for(var n=0; n<document.getE lementsByName(" company").lengt h; n++){
if (document.getEl ementsByName("c ompany")[n].value == 'msde')
{
document.getEle mentsByName("co untry")[n].checked = "checked";
}
}

May 4 '06 #1
22 8000
ASM
Saul a écrit :
I have a set of radio buttons that are created dynamically, after
rendered I try loop thru this set by getting the length of the set, but
I keep getting an error stating the element is undefined. I am using
getElelementsBy Name since these are radio buttons, but it seems that
the dynamic element is not seen!!!

This is my code... please let me know if there is anything that I am
doing wrong! - thanks
----
...
...
// this loops thru an ajax structure --- this is correct so I kow is
not an Ajax issue.

for(var i=0; i<ds.Tables[0].Rows.length; i++){
//creating nue input element
var r=document.crea teElement('<INP UT type=radio name=company >');
var r=document.crea teElement('INPU T');
r.type="radio";
r.name ="company";
r.id ="myradiobutton " + i;
r.setAttribute( "value",ds.Tabl es[0].Rows[i].roottype);
roottype isn't it Java language ?
td_company.appe ndChild(r);
what is td_company ?
td_company.appe ndChild(documen t.createTextNod e(ds.Tables[0].Rows[i].roottypedesc)) ;
}

-----
My function trying to get the lenght of the set is called after the
radion buttons are rendered. If I find one that has an specific value,
I check it.

for(var n=0; n<document.getE lementsByName(" company").lengt h; n++){
if (document.getEl ementsByName("c ompany")[n].value == 'msde')
{
document.getEle mentsByName("co untry")[n].checked = "checked";
}
}


var R = document.getEle mentsByName("co mpany");
var C = document.getEle mentsByName("co untry");
for(var n=0; n<R.length; n++)
if (R[n].value == 'msde') C[n].checked = "checked";

to avoid to re-built these two collections (R & C)
on each loop
--
Stephane Moriaux et son [moins] vieux Mac
May 5 '06 #2
Saul said on 05/05/2006 7:01 AM AEST:
I have a set of radio buttons that are created dynamically, after
rendered I try loop thru this set by getting the length of the set, but
I keep getting an error stating the element is undefined. I am using
getElelementsBy Name since these are radio buttons, but it seems that
the dynamic element is not seen!!!

This is my code... please let me know if there is anything that I am
doing wrong! - thanks
----
...
...
// this loops thru an ajax structure --- this is correct so I kow is
not an Ajax issue.

for(var i=0; i<ds.Tables[0].Rows.length; i++){
Is ds.Tables an array of table elements? If so, and item[0] is a table,
then it has a 'rows' collection, not 'Rows' (note capitalisation) . But
maybe it is some part of your XML structure that is called 'Rows', I
don't know.

Since you sequentially access all rows, it is also better to get a
reference to the row once and go from there.

It is more efficient to get the length attribute once and store it (the
saving may be insignificant if the number of rows is small, but it's the
thought that counts :-) ):

var row, rows = ds.Tables[0].rows;
for(var i=0, len=rows.length ; i<len; i++){
row = rows[i];

//creating nue input element
var r=document.crea teElement('<INP UT type=radio name=company >');
That method of dynamically adding elements is IE specific and will fail
in most (possibly all) other browsers, the W3C DOM standard method is:

var r = document.create Element('input' );
r.type = 'radio';
r.name = 'company';

However, if that method is used, IE doesn't recognise the name attribute
in script, though the form will submit correctly. There is a thread
about it here:

<URL:http://groups.google.c o.uk/group/comp.lang.javas cript/browse_frm/thread/db95b9f62035bee 6/a86500f9f588024 6?q=name+create Element&rnum=2# a86500f9f588024 6>

r.type="radio";
r.name ="company";
r.id ="myradiobutton " + i;
r.setAttribute( "value",ds.Tabl es[0].Rows[i].roottype);
setAttribute is buggy in some browsers, it is better (though
non-standard) to access properties directly as you have above:

r.value = ds.Tables[0].Rows[i].roottype;

td_company.appe ndChild(r);
td_company.appe ndChild(documen t.createTextNod e(ds.Tables[0].Rows[i].roottypedesc)) ;
Using the suggested row & rows variables above, this becomes:

td_company.appe ndChild(documen t.createTextNod e(row.roottyped esc));

}

-----
My function trying to get the lenght of the set is called after the
radion buttons are rendered. If I find one that has an specific value,
I check it.

for(var n=0; n<document.getE lementsByName(" company").lengt h; n++){
if (document.getEl ementsByName("c ompany")[n].value == 'msde')
{
document.getEle mentsByName("co untry")[n].checked = "checked";


Similarly here:

var el, els = document.getEle mentsByName("co mpany");
for(var n=0, len=els.length; n<len; n++){
el = els[i];
if (el.value == 'msde') {
el.checked = true;
}

--
Rob
Group FAQ: <URL:http://www.jibbering.c om/FAQ>
May 5 '06 #3
ASM
RobG a écrit :
Saul said on 05/05/2006 7:01 AM AEST: [...]
for(var n=0; n<document.getE lementsByName(" company").lengt h; n++){
if (document.getEl ementsByName("c ompany")[n].value == 'msde')
{
document.getEle mentsByName("co untry")[n].checked = "checked";

Similarly here:


Similarly but not duplicately ( "company" != "country" )
var el, els = document.getEle mentsByName("co mpany");
for(var n=0, len=els.length; n<len; n++){
el = els[i];
if (el.value == 'msde') {
el.checked = true;
}


var el, els = document.getEle mentsByName("co mpany");
var en, ens = document.getEle mentsByName("co untry");
for(var n=0, len=els.length; n<len; n++){
el = els[n]; // and not els[i]
if (el.value == 'msde') {
en = ens[n];
en.checked = true;
}
}
--
Stephane Moriaux et son [moins] vieux Mac
May 5 '06 #4
ASM said on 05/05/2006 12:31 PM AEST:
RobG a écrit :
Saul said on 05/05/2006 7:01 AM AEST:


[...]
for(var n=0; n<document.getE lementsByName(" company").lengt h; n++){
if (document.getEl ementsByName("c ompany")[n].value == 'msde')
{
document.getEle mentsByName("co untry")[n].checked = "checked";


Similarly here:

Similarly but not duplicately ( "company" != "country" )


Yeah, well, depends on the country, doesn't it? ;-)

var el, els = document.getEle mentsByName("co mpany");
for(var n=0, len=els.length; n<len; n++){
el = els[i];
if (el.value == 'msde') {
el.checked = true;
}

var el, els = document.getEle mentsByName("co mpany");
var en, ens = document.getEle mentsByName("co untry");
for(var n=0, len=els.length; n<len; n++){
el = els[n]; // and not els[i]
if (el.value == 'msde') {
en = ens[n];
en.checked = true;


If I'd seen company/country I'd likey have done:

var companys = document.getEle mentsByName("co mpany");
var countries = document.getEle mentsByName("co untry");
var n = companys.length ;
while (n--){
countries[n].checked = (companies[n].value == 'msde');
}

Of course it's not very tollerant of cases where companys.length is less
than countires.lengt h, but neither was the OP. :-)
--
Rob
Group FAQ: <URL:http://www.jibbering.c om/FAQ>
May 5 '06 #5
RobG said on 05/05/2006 12:49 PM AEST:
[...]
var companys = document.getEle mentsByName("co mpany");
var companies = ...
var countries = document.getEle mentsByName("co untry");
var n = companys.length ;
var n = companies.lengt h;
while (n--){
countries[n].checked = (companies[n].value == 'msde');
}

Of course it's not very tollerant of cases where companys.length is less


... companies.lengt h ...

--
Rob
Group FAQ: <URL:http://www.jibbering.c om/FAQ>
May 5 '06 #6
thanks for your replies...

ds is a dataset coming from an Ajax call and roottype is an element of
this set... I am sure the Ajax call is not the issue(since the data is
obtained and rendered correctly) and this is why I focused in the
javascript part to find the problem.

The elements are createed correctly when I loop thru the array. The
radio buttons are there and are visible inside the div tag "td_company "
The issue arises when trying to reference the element "company" which
is the name given to all the radio buttons created dynamically.

if I write an alert from inside the function creating the radio
buttons, to output the company.length ... I get the correct value.
If I write the alert outside the function I always get a zero. So
trying"

document.getEle mentsByName("co mpany").length

in the caller function always returns zero and therefore i cannot loop.
- but the radio buttons are there, how can it be zero!
Also using document.getEle mentsByName("co mpany")[0].value to find out
the value of the first element of the set of radio buttons returns
document.getEle mentsByName(... )[...].value is undefined.

I tried the different recommendations above, but still get the same
issue! - Any other suggestions

May 5 '06 #7
thanks for your replies...

ds is a dataset coming from an Ajax call and roottype is an element of
this set... I am sure the Ajax call is not the issue(since the data is
obtained and rendered correctly) and this is why I focused in the
javascript part to find the problem.

The elements are createed correctly when I loop thru the array. The
radio buttons are there and are visible inside the div tag "td_company "
The issue arises when trying to reference the element "company" which
is the name given to all the radio buttons created dynamically.

if I write an alert from inside the function creating the radio
buttons, to output the company.length ... I get the correct value.
If I write the alert outside the function I always get a zero. So
trying"

document.getEle mentsByName("co mpany").length

in the caller function always returns zero and therefore i cannot loop.
- but the radio buttons are there, how can it be zero!
Also using document.getEle mentsByName("co mpany")[0].value to find out
the value of the first element of the set of radio buttons returns
document.getEle mentsByName(... )[...].value is undefined.

I tried the different recommendations above, but still get the same
issue! - Any other suggestions

-thanks

May 5 '06 #8
Saul wrote:
thanks for your replies...
Please quote the relevant parts of what you are replying to.

ds is a dataset coming from an Ajax call and roottype is an element of
this set... I am sure the Ajax call is not the issue(since the data is
obtained and rendered correctly) and this is why I focused in the
javascript part to find the problem.
I'll guess that -ds.Tables[0].Rows- is referring to your XML structure,
not the HTMLElement structure suggested by the names you've used.

The elements are createed correctly when I loop thru the array. The
radio buttons are there and are visible inside the div tag "td_company "
The issue arises when trying to reference the element "company" which
is the name given to all the radio buttons created dynamically.
Exactly. IE has trouble with the name attribute of elements added
dynamically - from Microsoft's documentation:

"The NAME attribute cannot be set at run time on elements
dynamically created with the createElement method. To create
an element with a name attribute, include the attribute and
value when using the createElement method."

<URL:http://msdn.microsoft. com/workshop/author/dhtml/reference/properties/...>
Read the thread I suggested provides 2 work-arounds, here it is again;

<URL:http://groups.google.c o.uk/group/comp.lang.javas cript/browse_frm/thread/db95b9f62035bee 6/a86500f9f588024 6?q=name+create Element&rnum=2# a86500f9f588024 6>
[...]
I tried the different recommendations above, but still get the same
issue! - Any other suggestions


Try one of the methods in the suggested thread. Here's mine, I'm sure
you can adapt it to your circumstance:
<script type="text/javascript">

function addRadios(form, grpName, num)
{
var oRadio, e;
var dom = true;
for (var i=0; i<num; ++i){
if (dom){

// Create radio button, give it a name and add to form
oRadio = document.create Element('input' );
oRadio.name = grpName;
form.appendChil d(oRadio);

// Test if can access radio button group
// If not, remove element and set dom
if ( 0 == i && !document.getEl ementsByName(gr pName).length){
dom = false;
form.removeChil d(oRadio);
}
}

// If dom set to false, use IE method to add element
if (!dom){
try {
oRadio = document.create Element('<input type="radio"'
+ ' name="' + grpName + '">');
form.appendChil d(oRadio);
} catch (e){ e = true;}

// If got to here and no error, add attributes to element
// and element to document
}
if (!e){
oRadio.type = 'radio';
oRadio.onclick = rbClicked;
oRadio.value = grpName + ' ' + i;
form.appendChil d(document.crea teTextNode('rad-' + i));
form.appendChil d(document.crea teElement('br') );
}
}
}

// A play onclick function to show name is set
function rbClicked(){
alert('Clicked me!'
+ '\nName: ' + this.name
+ '\nValue: ' + this.value);
}
</script>

<form action="" name="aFrom"><d iv>
<input type="button" value="Add radios"
onclick="addRad ios(this.form, 'rBtnGrp', 4);"><br>
<input type="button" value="Click second radio"
onclick="
alert('There are ' + document.getEle mentsByName('rB tnGrp').length
+ ' radio buttons');
this.form.rBtnG rp[1].click();
"><br>
</div></form>

--
Rob
May 5 '06 #9
RobG wrote:

Exactly. IE has trouble with the name attribute of elements added
dynamically - from Microsoft's documentation:

"The NAME attribute cannot be set at run time on elements
dynamically created with the createElement method. To create
an element with a name attribute, include the attribute and
value when using the createElement method."

<URL:http://msdn.microsoft. com/workshop/author/dhtml/reference/properties/...>


Sorry, should be:

<URL:http://msdn.microsoft. com/workshop/author/dhtml/reference/properties/name_2.asp>
--
Rob
May 5 '06 #10

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

Similar topics

3
11961
by: Eric Chang | last post by:
I was working on this simple form with radio boxes. And when I click on one of the radio box, it tell me the value is "undefined" Why is that ? I did defined the value of each radio box: <input type=radio name='Usetax' value='basic' onClick='document.myform.amount.value=document.myform.Usetax.value'> <input type=radio name='Usetax' value='no' onClick='document.myform.amount.value=document.myform.Usetax.value'> <input type=radio...
6
4087
by: TheKeith | last post by:
I am doing a form for my site and would like to enable and disable a radio button set depending on whether one of the choices on an outer radio button set is checked. How can I refer to all the inputs of the inner radio button set (they all share a common name) with javascript. I tried document.getElementsByNames('thename') but it doesn't work. I know this is because this method returns an array which you must then refer to by a specific...
4
7306
by: Steph | last post by:
Hello, Can someone tell me the script to use for having a change on the same page when using checkbox function ? For example, i would to check one condition and display dynamically a button if the condition is checked on the same page. Thanks in advance for your help
6
3299
by: Craig Keightley | last post by:
I have a page that has n number of radio groups (yes/No) how can i prevent the form being submitted if more than one radio group is not selected? By default all radio groups are unchecked The problem i am facing is that i do not know how many yes/no radio groups will be generated
11
2267
by: Jon Hoowes | last post by:
Hi, I have inherited some code that has some form elements (radio buttons) that are called "1", "2" etc. for example: <input name="2" type="radio" value="45"> <input name="2" type="radio" value="46">
21
11424
by: briggs | last post by:
<html> <head> <script> /* AddChild */ function ac() { var c; var p = document.getElementById("p"); for (var i = 0; i < 5; i++) { c = document.createElement("DIV"); // Create 'div' element.
10
1635
by: Jen | last post by:
I have a form that has two radio buttons. When the first one is clicked, I would like the page to refresh (keeping the form data in tact) and then displaying 2 new fields that need to be filled out. If the second button is clicked, I need the same thing to happen, only it will display two different fields needing to be filled out. Does anyone have code that will do this? Or is this even possible with JavaScript? Thanks!!
0
1622
by: LavanyaM | last post by:
Hi, In our app we need to create dynamic radio buttons. There should be three radio buttons and this set is dynamic accroding to the data this is my code: <th width="5%" class="twolbcolors"><html:radio property="button" value="confirm"></</html:radio></th> <th width="5%" class="twolbcolors"><html:radio property="button" value="wait"></html:radio></th> <th width="5%"...
2
4999
Frinavale
by: Frinavale | last post by:
I'm attempting to intercept the click event for RadioButons in an attempt to ask the user for confirmation of their action. I determined that Internet Explorer does not reset the previous selection if the user was to cancel the action. In order to reset the previous select (cancel the new selection) I have to save a reference to the original selected radio button....well actually right now I'm just attempting to save the ID of the...
0
9994
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
9842
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
11265
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
10488
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
8036
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
7191
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
5882
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
4712
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
3
3309
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.