Forum Moderators: open
Is there any way to get JS to count how many of those fields have been completed (are not null), assign the number to a variable, and use that variable in the hidden form field for the confirmation page URL? If so, how would that be done? I tried several things, but don't know enough JavaScript yet to come up with anything that works.
Thanks for any help or advice,
Matthew
<script>
function countCompletedFormFields(formName, classToCheck)
{
var formObject = document.getElementById(formName);
var count = 0;
for (i=0;i<formObject.childNodes.length;i++)
{
currentNode = formObject.childNodes[i];
if(currentNode.nodeType==1 && currentNode.className == classToCheck && currentNode.value!= '')
{
count=count+1;
}
}
alert(count);
return(count);
}
</script>
<form id="myForm" method="get" action="" onSubmit="countCompletedFormFields('myForm','checkThis');this.submit();"/>
<input id="box1" class="checkThis" type="text"/>
<input id="box2" type="text"/>
<input id="box3" class="otherClass" type="text"/>
<input id="box4" class="checkThis" type="text"/>
<select name="select" class="checkThis">
<option>Please Select...</option>
<option value="1">1</option>
</select>
<input id="box5" type="text"/>
<input id="" type="submit" />
</form>
I tried pasting your code just as it sat directly into a new webpage. It worked perfectly. So I pasted the <script>...</script> above my form, added the onSubmit to my form tag, and changed myForm to match the ID of my form. Then I added
class="checkThis" to a couple form fields. When I tested it, the alert box came up, but it invariably says "0" instead of the actual number of checkThis fields that were completed. My form fields have no other classes or id's assigned to them. They also have a name attribute. I'm not sure if any of this matters; I tried removing the name attributes to no avail.
What factors might be causing the count to always be zero?
Thanks again for your help,
Matthew
<FORM>
<INPUT TYPE="button" onClick="javascript:chkForm(this.form);" VALUE="Submit">
</FORM>
<SCRIPT LANGUAGE="Javascript">
function chkForm(form) {
var msg = '';
var requireds = new Array('required','field','names','here');
var plainEnglish= new Array ('Names with','Spaces and','intelligible','English');
for (i=0;i<requireds.length;i++) {
//define the form object
var obj = eval('form.'+requireds[i]);
if ((obj.type == 'select-one') && (obj.selectedIndex == 0)) {
msg += '\nPlease select a '+plainEnglish[i]+ ' from the drop-down list.';
}
else if (obj.value == '') {
msg += '\nPlease enter your '+plainEnglish[i]+'.';
}
}
if (msg!= '') { alert(msg); }
else { form.submit(); }
}
</SCRIPT>
Crustov's script works as posted, but somehow it's not working on my form. I can't see any real differences between Crustov's posted form and mine, though . . .