PDA

View Full Version : How to access value



patter
12-22-2006, 02:27 AM
I am trying to write a function that can be used by a number of diiferent sections of code. Here is what I have
function update(numb) {
var x;
var box = new Array();
box[1] = "price1";

ttl = document.forms["product"].box[numb].value;
document.forms["product"].total = ttl;
}Then I call it with
<input type="text" id="price1" onkeyup="update(1)">The problem is that it doesn't work. If I change this line
ttl = document.forms["product"].box[numb].value;to
ttl = document.forms["product"].price1.value;then it works. Can anyone please point out my mistake?

mwinter
12-22-2006, 02:29 PM
I am trying to write a function that can be used by a number of diiferent sections of code.

Why not start by stating exactly what you want to create. Identifying the current problem is simple, but correcting that may not put you on the right track to solving the real issue.





function update(numb) {
var x;


Presumably that should be 'ttl' not 'x', or the identifier used below - 'ttl' - should be 'x'.





var box = new Array();
box[1] = "price1";

ttl = document.forms["product"].box[numb].value;


You haven't really considered what that member expression means.


Resolve Identifier 'document': document object.
Get property of 'document' named 'forms': forms collection.
Get property of 'forms' collection named 'product': form object.
Get property of form object named 'box': undefined (there is no such property).
Fatal error: attempting to access a property ('1') of undefined.




document.forms["product"].total = ttl;

That also seems to be a mistake: you should assigning to the value property of the form control. Certainly, don't create a property on the form object itself.



<input type="text" id="price1" onkeyup="update(1)">

Don't update whilst the user is editing. It'll only cause problems if the user enters invalid data. Instead, do it in response to the change event. Even better: create a button specifically for the action.

If this is for an order form, it should all be implemented server-side and this update process can be omitted entirely - the server can show the total cost during the confirmation process.



If I change this line



ttl = document.forms["product"].box[numb].value;

to



ttl = document.forms["product"].price1.value;

then it works. Can anyone please point out my mistake?

Use bracket notation create the property name:



ttl = document.forms.product.elements['price' + numb].value;

Mike

patter
12-23-2006, 02:00 AM
Thank you for the in-depth explanation. I was able to get it to work with that.