2 replies [Last post]
mayonaise
Offline
Regular
Last seen: 15 years 48 weeks ago
Joined: 2004-08-06
Posts: 29
Points: 0

reading from form elements like an INPUT or TEXTAREA is easy, but i'm not doing anything that straightforward. i have some javascript to dynamically generate text input fields. the script also has to read the data that was entered into these dynamically generated input fields (if any), and this is where the problem comes in. these objects are NOT static, and there can be an arbitrary number of them. in order to access them, i'm using something like this:

for (i = 0; i < listCount; i++)
{
	var input = document.formName.eval("listItem" + i);
	// fails on this if statement
	if (input.value)
		result = input.value;
}

each input field is generated with name="listItemX", where X is an integer that increases with each added input field. "formName" is obviously the name of the form in which the input field is contained.

this code works in firefox, but fails in IE. it seems that while IE WILL let me call eval() in this fashion, the resulting value returned into the variable "input" is not correct. the script fails on the line if (input.value)...

is there a way to do this? hardcoding is not an option, because it needs to be dynamic.

this is an example of the script if the name of the input field is hardcoded - which works in both browsers

var input = document.formName.listItem1;
if (input.value)
	result = input.value;

thanks!

Tags:
Tony
Tony's picture
Offline
Moderator
Brisbane
Last seen: 1 week 2 days ago
Brisbane
Timezone: GMT+10
Joined: 2003-03-12
Posts: 5343
Points: 2964

javascript, IE: reading from dynamic form elements

Hi mayonaise,
Have you tried using var input = document.getElementById("listItem" + i); or if you want to get all input boxes you could use document.getElementsByTagName('INPUT' );
Hope that helps

mayonaise
Offline
Regular
Last seen: 15 years 48 weeks ago
Joined: 2004-08-06
Posts: 29
Points: 0

javascript, IE: reading from dynamic form elements

Tony wrote:
Hi mayonaise,
Have you tried using var input = document.getElementById("listItem" + i); or if you want to get all input boxes you could use document.getElementsByTagName('INPUT' );
Hope that helps
thanks for the tips..

document.getElementById("listItem" + i);fails in firefox when you attempt to access the "value" property.

using
document.getElementsByTagName("input"); works in both browsers. i run through the node list that is returned, searching for any node with attribute name=="listItem" + i.

i'm not exactly sure why one works and the other doesn't, because according to the gecko DOM reference, getElementById() returns an element, and getElementsByTagName() returns a list of elements. so i can access the "value" property of some elements, but not some others? unless they're using the term "element" as a generic, or the two functions return some subclasses that i'm unaware of, i don't know why this is happening