--- In [email protected], "Marius Bocean" <[EMAIL PROTECTED]> wrote:
> I have this JS code that check all the chechboxes am make the sum of
their
> values.
> The checkall function works fine, but when i try to add'em up, the
function
> that do that, it concatenate them(treat them like string not like
numbers I
> supose).
> This is the code:
> <html>
> <HEAD>
> <SCRIPT LANGUAGE="JavaScript">
> var checkflag = "false";
> function check(field) {
> if (checkflag == "false") {
> for (i = 0; i < field.length; i++) {
> field[i].checked = true;}
> checkflag = "true";
> return "Uncheck"; }
> else {
> for (i = 0; i < field.length; i++) {
> field[i].checked = false; }
> checkflag = "false";
> return "Check All"; }
> }
> function f(frmObj)
> {
>
> var strVal = "";
>
> var el = frmObj.elements;
> var nFields = el.length;
>
>
> for ( n = 0 ; n < nFields ; n++ )
> {
> if (el[n].type == "checkbox" && el[n].checked)
> {
> strVal += el[n].value;
> }
> }
> document.form1.how.value = strVal;
> }
> </script>
> </HEAD>
>
>
>
> <BODY>
>
> <center>
> <form name="form1" action="" method=post>
> <table>
> <tr><td>
> <b>Test</b><br>
> <input type="checkbox" name="list" value="1"
onClick="f(this.form);">1<br>
> <input type="checkbox" name="list" value="2"
onClick="f(this.form);">2<br>
> <input type="checkbox" name="list" value="3"
onClick="f(this.form);">3<br>
> <input type="checkbox" name="list" value="4"
onClick="f(this.form);">4<br>
> <input type="checkbox" name="list" value="5"
onClick="f(this.form);">5<br>
> <br>
> <input type="button" value="Check All"
> onClick="this.value=check(this.form.list);f(this.form)">
> <input type="text" name="how">
> </td></tr>
> </table>
> </form>
> </center>
>
> </body>
> </html>
>
> What the .... am i doing wrong?
The values stored in your checkboxes are stored as strings, so when
you ask javascript to add these strings together it quite rightly does
just that and concatenates them. What you need to to is to convert
the string to an integer when you're adding them in your loop using
parseInt().
Try:
strVal += parseInt(el[n].value);
David
The php_mysql group is dedicated to learn more about the PHP/MySQL web database
possibilities through group learning.
Yahoo! Groups Links
<*> To visit your group on the web, go to:
http://groups.yahoo.com/group/php_mysql/
<*> To unsubscribe from this group, send an email to:
[EMAIL PROTECTED]
<*> Your use of Yahoo! Groups is subject to:
http://docs.yahoo.com/info/terms/