簡體   English   中英

HTML。 如何檢查用戶是否以表格形式輸入文字?

[英]HTML. How to check If user entered text in form?

因此,我的表單中包含First_NameLast_NameCityEmail 我需要檢查字段是否為空。

現在,單擊提交, GetFbId.php從此處重定向到GetFbId.php ,我將有5個值插入數據庫: FB_IdFirst_NameLast_NameCityEmail

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="#">來代替action="GetFbId.php"> ,但是在這種情況下,單擊提交按鈕后什么也沒有發生。

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']; 

但是,當單擊“提交”按鈕時,沒有任何動作(什么也沒有發生)。 您有解決方法的想法嗎?

您需要阻止默認的提交操作。 否則,無論您使用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/

您還可以通過在必填字段中添加“必填”,讓瀏覽器為您處理必填字段。 然后,您只需要處理$ .post()方面。 但是,並非所有舊版瀏覽器(例如IE8)都支持此功能,因此不能保證阻止表單以空值提交。

例如:

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

並且,當然,您還需要在服務器端(PHP)上驗證輸入。

在表單中添加一個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');
                })
             ;
        }
    });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM