do not submit form until function returns true

时间:2018-02-03 11:29:04

标签: javascript jquery html forms

i have this javascript code which has a function that calls other functions. The problem is the input.html form is getting submitted even if the fields are empty.. if I dont provide any input in the fields, the error messages are being shown but at the same time form gets submitted. there are numerous questions like this available but none is helping as they are not calling function within the function.. what can be the possible solution for this?

function blankos() {
  var p = document.getElementById("windows");
  var q = document.getElementById("linux");

  if ((p.checked == false) && (q.checked == false)) {
    document.getElementById("enteros").innerHTML = "Select an option";
    return false;
  } else if ((p.checked == true) || (q.checked == true)) {
    document.getElementById("enteros").innerHTML = "";
    return true;
  }

}

function blankfreq() {
  var r = document.getElementById("biannual");
  var s = document.getElementById("monthly");

  if ((r.checked == false) && (s.checked == false)) {
    document.getElementById("enterfreq").innerHTML = "Select an option";
    return false;
  } else if ((r.checked == true) || (s.checked == true)) {
    document.getElementById("enterfreq").innerHTML = "";
    return true;
  }
}

function blankhour() {
  var i = document.getElementById("one");
  var ii = document.getElementById("two");
  var iii = document.getElementById("four");

  if ((i.checked == true) || (ii.checked == true) || (iii.checked == true)) {
    document.getElementById("enterhour").innerHTML = "";
    return true;
  }
  return false;

}


function blank() {
  blankos();
  blankfreq();
  blankhour();
  checkselect();

}
<form onSubmit="return blank()" name="input" id="input" method="post" action="cgi-bin/review.cgi" >

2 个答案:

答案 0 :(得分:1)

blank()不会返回任何内容。尝试:

function blank() {
    return blankos() && blankfreq() && blankhour() && checkselect();
}

这只会报告检测到的第一个错误。如果您希望报告所有这些,请先将它们分配给变量。

function blank() {
  var ok1 = blankos();
  var ok2 = blankfreq();
  var ok3 = blankhour();
  var ok4 = checkselect();
  return ok1 && ok2 && ok3 && ok4;
}

但我没有查看所有单独的验证功能。你可能还有一些需要修复的错误。

答案 1 :(得分:0)

您可以使用preventDefault()限制您的表单提交。从

更改HTML
<form onSubmit="return blank()" name="input" id="input" method="post" action="cgi-bin/review.cgi" >

<form name="input" id="input" method="post" action="cgi-bin/review.cgi" >

然后添加此代码块

//id of the form is 'input'
$("#input").submit(function(e){
//if any of the inner functions return false then prevent from form submit
   if( !blankos() || !blankfreq() || !blankhour() || !checkselect()){
      e.preventDefault();
      return  false;
   }
});