开发者

Returning HTML Ends Loop Premature

I am using javascript to validate some form elements. The fields I want to be required are passed into my validateReqFields function when the form is submitted. Everything is working perfectly until I get to the for loop that is meant to add an error message the an empty beside the form field. It seems that as soon as one field fails and it adds the message to the div, the for loop does not continue.

The HTML Form Elements:

First Name 开发者_开发问答<input type="text" name="firstName"  onkeypress="return checkField(event, letters);"/><div id="firstNameMsg" style="display:inline-block;"></div>
<br>
Last Name <input type="text"  name="lastName" onkeypress="return checkField(event,        letters);"/><div id="lastNameMsg" style="display:inline-block;"></div>

The Javascript function:

function validateReqFields(formName, reqFields){
var fieldArray = reqFields.split(",");
var failedList = new Array();
var message = "Required Field";

for(var i=0; i<fieldArray.length; i++){
    removeWhiteSpace(fieldArray[i]);
    var s = eval('document.'+formName+'.'+fieldArray[i]+'.value');
    if(s.length<1) { failedList.push(fieldArray[i]); }
}

if(failedList.length >= 1) { 

    for(var i=0; i<failedList.length; i++) {
        //BUG - Only shows first failed field.
        document.getElementById(failedList[i] + 'Msg').innerHTML = message;
    }

} else {
    document.mForm.submit();
}
}

function removeWhiteSpace(mString){
mString = mString.replace(/(^\s+|\s+$)/g,' ');
return mString;
}

I have done a few tests and concluded that when the for loops sets the innerHtml on the first div element, it breaks the for loop. Is there a way to avoid this?


My removeWhiteSpace function was not working correctly, thus everything after my first field was failing. Silly mistake. Please close this question.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜