Client side calculation

Results 1 to 2 of 2

Thread: Client side calculation

  1. #1
    Join Date
    Dec 1969

    Default Client side calculation

    I have 7 text boxes adj1Val, adj2Val....adj7Val. <BR>User enters values in any of these boxes and clicks on calculate button next to total. <BR>total = adj1Val + adj2Val...+ adj7Val<BR><BR>here&#039s the code<BR>&#060;script Language="JavaScript"&#062;&#060;!--<BR><BR>function f(a) {<BR> if (a.value == "") {<BR> return 0;<BR> }<BR> else<BR>{<BR> return a.value;<BR> }<BR>}<BR><BR>function calculate(formObj)<BR><BR>{<BR> var adj1Val = parseFloat(formObj.txt_adj1_value.value);<BR> var adj2Val = parseFloat(formObj.txt_adj2_value.value);<BR> var adj3Val = parseFloat(formObj.txt_adj3_value.value);<BR> var adj4Val = parseFloat(formObj.txt_adj4_value.value);<BR> var adj5Val = parseFloat(formObj.txt_adj5_value.value);<BR> var adj6Val = parseFloat(formObj.txt_adj6_value.value);<BR> var adj7Val = parseFloat(formObj.txt_adj7_value.value);<BR> <BR> var tot_adj_value = f(adj1Val) + f(adj2Val) + f(adj3Val) + f(adj4Val) + f(adj5Val) + f(adj6Val) + f(adj7Val);<BR> <BR> formObj.tot_adj_value.value = tot_adj_value;<BR> <BR> return;<BR> <BR>}<BR><BR><BR>I call this function using onclick method. If user enters value in all 7 boxes, I get right total. But if user skips either one box, I get answer &#039NaN&#039. I thought function(f) will take care if that happens, but it doesn&#039t work.<BR><BR>Any suggestion will be appreciated.<BR>

  2. #2
    Join Date
    Dec 1969

    Default RE: Client side calculation

    Since you have ALREADY called parseFloat BEFORE you call function f, it is too late to check for "" as the value.<BR><BR>Further, in your function f you are doing<BR> a.value<BR>but you have already converted the form field&#039s ".value" to a simple number by that point, so that won&#039t work either.<BR><BR>Try just this:<BR><BR>function f(a) { return isNaN(a) ? 0 : a; }<BR><BR>in place of your function f. Leave the rest as shown.<BR><BR>Of course, you could shorten this a lot:<BR><BR>function calculate(formObj)<BR>{<BR>&nbsp;&nbsp;&nbsp;&nbsp ;var total = 0.0;<BR>&nbsp;&nbsp;&nbsp;&nbsp;for ( i = 1; i &#060;= 7; ++i )<BR>&nbsp;&nbsp;&nbsp;&nbsp;{<BR>&nbsp;&nbsp;&nbs p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var curval = parseFloat( eval("formObj.txt_adj" + i + "_value.value") );<BR>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&n bsp;if ( ! isNaN(val) ) total += val;<BR>&nbsp;&nbsp;&nbsp;&nbsp;}<BR>&nbsp;&nbsp;& nbsp;&nbsp;formObj.tot_adj_value.value = total;<BR>}<BR>

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts