PDA

View Full Version : Manipulating arrays of form elements with Javascript


ocularis
11-25-2002, 10:33 PM
Hi,
I have a dynamically created array of form elements (text boxes). I set an onblur event for each one. Since the elements all have the same name, how do I determine the subscript of the element which triggered the onblur event? I need to obtain the subscript itself to be able to synchronize this change with an adjacent array of text boxes. I am only vaguely familiar with the use of the "this" statement.

example:
(double quotes are there because I create the page as an ASP)

<input type=""text"" size=""5"" name=""Qty"" onBlur=""calcPrice();""/>

function calcPrice(){
var theIndex;
theIndex= document.orderfrm.Qty.Index;
window.alert('the index is' + theIndex);
document.orderfrm.Extprice[theIndex].value= document.orderfrm.Qty[theIndex].value *
jsarray[theIndex][4];
}

jsarray is an array I have populated from a database. The 4th column contains a price field. I guess there is no property called "Index" for form elements because I get a syntax error. Also the alert window says the value is null. How do I obtain the index/subscript for this element?

Thanks in advance for any help!

Borgtex
11-26-2002, 02:03 AM
You can acces the value of the textbox with this.value, the whole form with this.form and the array of textboxes with this.form.Qty
but I have no idea of how can you know the caller index.

Maybe it will sound stupid, but if you can dinamically create the form elements, why don't dynamically add the index as a parameter for the calcPrice() function?

I mean:

<input type="text" size="5" name="Qty" onBlur="calcPrice(this,0);"/>
<input type="text" size="5" name="Qty" onBlur="calcPrice(this,1);"/>

glenngv
11-26-2002, 02:17 AM
Borgtex is correct. Expanding on his solution:

function calcPrice(objTxt,theIndex){
objTxt.form.Extprice[theIndex].value= this.value * jsarray[theIndex][4];
}

ocularis
11-26-2002, 02:23 PM
That doesn't sound stupid at all. I am looping to create the form elements so I can just add my loop counter as part of the function call.

I will try it. Thank you.