我的jquery表单出错了

时间:2015-08-20 17:48:27

标签: jquery forms

表单将发送到php文件但是我在收到错误填写时收到错误消息时遇到问题。你能发现我可能遗失的任何基本错误吗?我是JQuery的新手,我不能使用插件。

$(document).ready(function() {
   var username = $('#username').val();
   var email = $('#email').val();


  function submitDetailsForm()
  {
  if (username == '') {
     $('#usernameError').html('Please insert your username!');
    }
    else {
     return true;
     }

  if (email == '') {
     $('#emailError').html('Please enter an email!');
    }
    else {
     return true;
     }
    return false;
  }

2 个答案:

答案 0 :(得分:1)

有很多错误,但你可以从这段代码中获得想法。

$('#formId').submit(function(){
    var hasErrors = false; 
    var username = $('#username').val();
    var email = $('#email').val();

    if (username == '') {
        $('#usernameError').html('Please insert your username!');
        hasErrors = true; //username is empty, lets set our variable to true
    }

    if (email == '') {
        $('#emailError').html('Please enter an email!');
        hasErrors = true; //email is empty, lets set our variable to true
    }

    if(!hasErrors){ //if the variable was false that means there was no error
        $("#usernameError,#emailError").html('');//Clear error message when form is valid
        return true; //continue with the form submission
    } else { //else if it is true, that means we have an error
        return false; //prevent the form submission
    }
});

FIDDLE

答案 1 :(得分:-1)

===比较字符串,而不仅仅是==

您也应该检查undefined的用户名和电子邮件