For loop ....

Results 1 to 3 of 3

Thread: For loop ....

  1. #1
    PersonalFoul Guest

    Default For loop ....

    ...I have a form that creates input fields dynamically so I don&#039;t know how many &#060;input&#062; boxes were created or their name when the form is submitted (I do know afterwards though, not applicable in this case).<BR><BR>I need to add the values of each dynamic box and then display that number as an Alert(variable) before actually submitting the form.<BR><BR>I&#039;m not sure of the JavaScript syntax to get each element.<BR><BR>I&#039;m toying with the following, but it obviously doesn&#039;t work and is only partial.<BR><BR>Any help with the for loop syntax or other to achieve this is appreciated.<BR><BR>I&#039;m assuming something like the following to begin the loop only substituting my form criteria for the 2 in this case.<BR><BR> for (i=0; i&#060;2; i++)<BR>{<BR>math operations here......<BR><BR>}<BR><BR>bs

  2. #2
    Join Date
    Dec 1969

    Default You need *something*...

    ...that distinguishes the form fields in question from other fields. Either give them all a prefix that is unique to their group or, perhaps, use a className that is unique.<BR><BR>Then it&#039;s easy.<BR><BR>&#060;SCRIPT&#062;<BR>function sum( )<BR>{<BR> var total = 0;<BR> var frm = document.YourFormName;<BR> for ( var fnum = 0; fnum &#060; frm.elements.length; ++fnum )<BR> {<BR> var fld = frm.elements[fnum];<BR> if (,2) == "V_" )<BR> {<BR> total += parseFloat( fld.value );<BR> }<BR> }<BR> alert( total );<BR>}<BR>&#060;/SCRIPT&#062;<BR><BR>In that example, I assumed that you gave each of the dynamic input fields the prefix "V_" for their name (e.g., &#060;INPUT Name="V_C17RZ"&#062;).<BR><BR>If you prefer to use a special class, then do something like<BR> &#060;INPUT Class="SumThis" ...&#062;<BR>and change the line in bold, above, to:<BR> if ( fld.className == "SumThis" )<BR>

  3. #3
    Join Date
    Dec 1969

    Default RE: For loop ....

    Will each dynamically created box have JUST a number as its name? Or is there text also, llke: TextBox_1, TextBox_2,...<BR><BR>If it&#039;s just a number val, then you could just do:<BR><BR>var HowManyFields;<BR><BR>HowManyFields = theForm.elements.length;<BR><BR>That will return a count of all the form elements. But it won&#039;t nitpick - it will return everything, including buttons an hidden fields.

Posting Permissions

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