PDA

View Full Version : alert function using arrays



jc_gmk
11-23-2007, 02:16 PM
I have a form that when it is submitted it displays an alert box

I want that alert box to display the value of the fields that were submitted

e.g.


<form action="somepage.php" name="orderqty" onsubmit="alert('you entered ' + orderqty.qty.value + '!')">
<input type="text" name="qty" />
<input type="submit" value="submit" />
</form>

This works fine, however the form that I am submitiing has multiple input boxes with the same name

e.g.


<input type="text" name="qty[]" />
<input type="text" name="qty[]" />
<input type="text" name="qty[]" />
<input type="text" name="qty[]" />
<input type="text" name="qty[]" />
<input type="text" name="qty[]" />


Is there anyway I can get the alert function to read the values of all the qty[] input fiels added together?

jscheuer1
11-23-2007, 03:22 PM
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

</head>
<body>
<form action="somepage.php" name="orderqty" onsubmit="
for (var n=0, e=this.elements, q='you entered:\n', i = 0; i < e.length; i++)
if (e[i].name && e[i].name=='qty[]')
q+=(++n)+': '+e[i].value+'\n';
alert(q);">
<div>
<input type="text" name="qty[]"><br>
<input type="text" name="qty[]"><br>
<input type="text" name="qty[]"><br>
<input type="text" name="qty[]"><br>
<input type="text" name="qty[]"><br>
<input type="text" name="qty[]"><br>
<input type="submit" value="submit">
</div>
</form>
</body>
</html>

jc_gmk
11-23-2007, 03:40 PM
Works great, thank you.

But how do I add the values together rather than displaying them line by line
as there could be upto a hundred lines at a time

e.g.
instead of:
1 : 3
2: 8
3: 14

i would like

25

This is hopefully straight forward as it is basic maths but I dont know how to code it as I don't really know javascript.

Thanks

jscheuer1
11-23-2007, 04:58 PM
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

</head>
<body>
<form action="somepage.php" name="orderqty" onsubmit="
for (var q=0, e=this.elements, i = e.length-1; i > -1; --i)
if (e[i].name && e[i].name=='qty[]' && !isNaN(+e[i].value))
q+= +e[i].value;
alert('you entered: '+q);">
<div>
<input type="text" name="qty[]"><br>
<input type="text" name="qty[]"><br>
<input type="text" name="qty[]"><br>
<input type="text" name="qty[]"><br>
<input type="text" name="qty[]"><br>
<input type="text" name="qty[]"><br>
<input type="submit" value="submit">
</div>
</form>
</body>
</html>

jc_gmk
11-23-2007, 05:03 PM
Perfect, thanks once again!!