HTML。如何检查用户是否在表单中输入了文字?

时间:2015-03-24 13:16:52

标签: javascript php jquery html forms

所以我的表单包含 First_Name Last_Name City Email 。我需要检查字段是否为空。

现在,点击提交后,从这里重定向到GetFbId.php我有5个要插入数据库的值: FB_Id First_Name Last_Name 城市电子邮件

Form.html

<!DOCTYPE html>
<html>
  <head>
    <title>Registracija</title>
    <meta name="robots" content="noindex, nofollow">

    <!-- include css file here-->
   <link rel="stylesheet" href="css/style.css"/>

    <!-- include JavaScript file here-->
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script type="text/javascript" src="js/registration.js"></script>

  </head>   
  <body>
    <div class="container">
        <div class="main">
          <form class="form"  method="post" action="#">
            <h2>Registracijos forma</h2><hr/>
            <label>First Name: </label>
            <input type="text" name="first_name" id="first_name" required>

            <label>Last Name: </label>
            <input type="text" name="last_name" id="last_name" required>

            <label>City: </label>
            <input type="text" name="city" id="city" required>

            <label>Email: </label>
            <input type="text" name="email" id="email" required>

            <input type="submit" name="register" id="register" value="Register">
          </form>   
        </div>
   </div>
  </body>
</html>

正如您现在所看到的,它有action="GetFbId.php"。我有JS脚本来检查它,但它不适合我。 JS被称为:registration.js

我在Form.html内的<head>代码中包含以下内容:

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script type="text/javascript" src="js/registration.js"></script>

而不是action="GetFbId.php">我尝试使用action="#">,但在这种情况下,点击提交按钮后没有任何反应。

registration.js *看起来像:

$(document).ready(function(){

$("#register").click(function(){
    var first_name = $("#first_name").val();
    var last_name = $("#last_name").val();
    var city = $("#city").val();
    var email = $("#email").val();

    if( first_name =='' || last_name =='' || email =='' || city =='')
        {
          alert("Fill all fields.");
        }   
    else if((first_name.length)<3)
        {
            alert("Too short first name.");
        }

    else if((last_name.length)<4)
        {
            alert("Too short last name.");
        }   
    else 
       {
         $.post("GetFbId.php",{first_name: first_name, last_name: last_name, city: city, email: email},
          function(data) {
           if(data=='Success')
           {
            $("form")[0].reset();
           }
           alert(data);
        });
       }

    });

});

GetFbId.php我试图获取以下变量:

$first_name = $_POST['first_name']; 
$last_name = $_POST['last_name']; 
$city = $_POST['city']; 
$email = $_POST['email']; 

但点击提交按钮时没有动作(没有任何反应)。你有想法如何解决它吗?

2 个答案:

答案 0 :(得分:0)

您需要阻止默认的提交操作。否则,无论您在JavaScript中执行什么操作,按钮单击都会提交表单。您的脚本都验证输入并使用jQuery的.post(),因此您需要使用以下命令阻止该默认提交操作:

event.preventDefault();

我还建议在验证失败时返回false。

更新了JavaScript:

$(document).ready(function () {

    $("#register").click(function () { 
        event.preventDefault(); // <--  ADDED THIS LINE
        var first_name = $("#first_name").val();
        var last_name = $("#last_name").val();
        var city = $("#city").val();
        var email = $("#email").val();

        if (first_name == '' || last_name == '' || email == '' || city == '') {
            alert("Fill all fields.");
            return false; // <-- ADDED THIS LINE
        } else if ((first_name.length) < 3) {
            alert("Too short first name.");
            return false; // <-- ADDED THIS LINE
        } else if ((last_name.length) < 4) {
            alert("Too short last name.");
            return false; // <-- ADDED THIS LINE
        } else {
            $.post("GetFbId.php", {
                first_name: first_name,
                last_name: last_name,
                city: city,
                email: email
            },

            function (data) {
                if (data == 'Success') {
                    $("form")[0].reset();
                }
                alert(data);
            });
        }

    });

});

请参阅演示:http://jsfiddle.net/BenjaminRay/n6jqvrra/

您还可以让浏览器通过在必填字段中添加“required”来为您处理所需的字段验证。然后你只需要处理$ .post()方面的事情。但是,所有旧浏览器(例如IE8)都不支持此功能,因此无法保证使用空值提交表单。

E.g:

<input type="text" name="first_name" id="first_name" required>

当然,您还需要验证服务器端(PHP)的输入。

答案 1 :(得分:-1)

在表单中添加ID:

<form class="form" id="form_id" method="post" action="GetFbId.php">

现在,不要在click上捕获#register事件,而是尝试捕获形式的submit事件

$('#form_id').submit(function(evt) { // Better to use a form id
    // First, avoid the form being submitted normally (forms change the website from which they are submitted)
    evt.preventDefault();

    // Now do your form checking...
});

所以你的代码看起来像是:

<强> HTML

<form class="form"  method="post" action="GetFbId.php" id="form_id">
<h2>Registration</h2><hr/>
<label>First Name: </label>
<input type="text" name="first_name" id="first_name">

<label>Last Name: </label>
<input type="text" name="last_name" id="last_name">

<label>City: </label>
<input type="text" name="city" id="city">

<label>Email: </label>
<input type="text" name="email" id="email">
<input type="submit" name="register" id="register" value="Register">
 </form>

<强> Registration.js

$(document).ready(function(){
    $("#form_id").submit(function(){ // Note the "submit" event OF THE FORM
        var $form = $(this); // Save the context of the form
        event.preventDefault(); // Prevent the form from being submitted normally

        var first_name = $( '#first_name' ).val();
        var last_name  = $( '#last_name' ).val();
        var city       = $( '#city' ).val();
        var email      = $( '#email' ).val();

        if (
            first_name.length == 0
            ||
            last_name.length == 0
            ||
            email.length == 0
            ||
            city.length == 0
        )
        {
            alert('All fields are required.');
        }
        else if ( first_name.length < 3 ) alert('First name is too short');
        else if ( last_name.length < 4 ) alert('Last name is too short');
        else 
        {
             $.post( "GetFbId.php", $form.serialize() )
                 .done(function(data) {
                     alert(data); // Print what the server returns
                })
                .fail(function() {
                     alert('An error has occured');
                })
             ;
        }
    });
});