简体   繁体   中英

jQuery validation alert issue

I am new to javascript and having hard time validating my form.

I have a from where I am asking questions from customer. There are 2 required question (range ones), I have already set requiredQuestions array in a loop which is referenced in javascript so as to validate only required questions)

Here is my form code:

 <form id="frmQuestion" method="post">
 <input type="range" id="#QuestionID# name="#QuestionID#" min="0" max="10">
 <textarea cols="40" rows="10" name="#QuestionDomID#" id="#QuestionDomID#"    </textarea>
  <input type="button" value="submit" id="frmQuestion_submit">
 </form>

And here is the javascript:

 <cfoutput>
    <script type="text/javascript">
    $('##frmQuestion_submit').click(function()
    {
        var jsArr;
        var jsArr = #SerializeJson(requiredQuestions)#;
        for(var i=0;i<jsArr.length;i++){
            var question = jsArr[i].FNAME;
            var qValue = $("##QuestionID#").val();

            if (qValue == 0){
                alert('Please fill all required fields');
                return false;
            }
            else{
            return true;
            }

        }

    });
</script>

I only want to alert once but here it is alerting twice - one for each question. If i add return false, its not alerting if first question is answered.

Loop through all of your array and set a flag indicating an error condition if one is found. After the loop executes, check the flag and act accordingly.

var validationFailed = false;
for(var i=0;i<jsArr.length;i++){
        var question = jsArr[i].FNAME;
        var qValue = $("##QuestionID#").val();

        if (qValue == 0){
            validationFailed = true;
        }
}
if (validationFailed)
{
   alert('Please fill all required fields');
   return false;
}
else
{
   return true;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM