Welcome to WebmasterWorld Guest from 54.162.157.249

Forum Moderators: open

Message Too Old, No Replies

dynamic input fields

retrieving the values

     
6:07 pm on Nov 18, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



i have a form that consists of dynamic input field names.

i.e.

weight1
weight2
weight3
etc.

i need to figure out how to obtain the total value of all the fields, before submitting the form.

my feeble attempts were variations of this:

var n = 0;
var i = 0;
var x = 0;
var form = "form100";
var prefix = "weight";

while (form[prefix + i++]) {
x = form[prefix + i++].value;
n = n + x;
}

then check the value of n. can anyone help?

-Matt

11:18 pm on Nov 18, 2003 (gmt 0)

10+ Year Member



weight1
weight2
weight3
...

These are foo-generated text fields? And the number varies from page to page?

What was the result of the script you have there? Is that script contained in a function?

11:37 pm on Nov 18, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



sorry, i figured out the problem, and here's the result:

// this function checks the values of the dynamically generated fields.
// the prefix is the field name i.e. <input type = "text" name = "weight<%=count%>">
// the Check100 function adds up all entered values in the fields, and makes sure the total value is 100. if it's not 100, throw error.

function Check100() {
var n = 0;
var i = 0;
var x = 0;
var prefix = "weight";

while (++i <= <%=n%>) { // this n variable is an ASP variable pulled from a form
x = (document.checkform[prefix + i].value) - 0; // subtracting zero from a string, converts it to type integer
n = eval(n + x); // keep track of cumulative total
}

if (n!= 100) {
alert('Your values must equal 100');
return false;
}
else {
return true;
}
}

-Matt

2:39 am on Nov 19, 2003 (gmt 0)

10+ Year Member



x = (document.checkform[prefix + i].value) - 0; // subtracting zero from a string, converts it to type integer
n = eval(n + x); // keep track of cumulative total

The toInt hack is a neat trick.

Why eval()? Just added insurance in case that doesn't work and x is still a string?

3:23 am on Nov 19, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



i couldn't find quickly enough how to convert a string to integer in javascript, but i did find that little trick first. i was having a problem where my values were concatenating, instead of adding, and the subtract zero thing worked.

yeah, i figured the eval() doesn't hurt anything, so i kept in there. like you said, it's just added insurance.

-Matt

 

Featured Threads

Hot Threads This Week

Hot Threads This Month