简体   繁体   English

HTML。 如何检查用户是否以表格形式输入文字?

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

So I have form with First_Name , Last_Name , City and Email . 因此,我的表单中包含First_NameLast_NameCityEmail I need to check If fields are not empty. 我需要检查字段是否为空。

For now, after clicking submit It redirecting to GetFbId.php from here I have 5 values to insert to database: FB_Id , First_Name , Last_Name , City and Email 现在,单击提交, 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>

As you see for now It have action="GetFbId.php" . 如您现在所见,它具有action="GetFbId.php" I have JS script to check It, but It not working for me. 我有JS脚本来检查它,但是它对我不起作用。 JS is called: registration.js JS称为: registration.js

I'm including in Form.html , inside <head> tags following: 我包括在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>

And instead of action="GetFbId.php"> I've tried to use action="#"> , but in this case nothing happens after I click submit button. 并且我尝试使用action="#">来代替action="GetFbId.php"> ,但是在这种情况下,单击提交按钮后什么也没有发生。

registration.js * looks like: 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);
        });
       }

    });

});

And in GetFbId.php I'm trying to get variables in following: GetFbId.php我尝试在以下变量中获取变量:

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

But no action (nothing happens) when submit button is clicked. 但是,当单击“提交”按钮时,没有任何动作(什么也没有发生)。 Have you ideas how to fix It? 您有解决方法的想法吗?

You need to prevent the default submit action. 您需要阻止默认的提交操作。 Otherwise, the button click submits the form, regardless of what you are doing in JavaScript. 否则,无论您使用JavaScript做什么,单击按钮都将提交表单。 Your script both validates the input and uses jQuery's .post(), so you need to prevent that default submit action with: 您的脚本既可以验证输入,也可以使用jQuery的.post(),因此您需要使用以下命令来阻止默认的提交操作:

event.preventDefault();

I would also recommend returning false when validation fails. 我也建议验证失败时返回false。

Updated JavaScript: 更新的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);
            });
        }

    });

});

See demo: http://jsfiddle.net/BenjaminRay/n6jqvrra/ 观看演示: http : //jsfiddle.net/BenjaminRay/n6jqvrra/

You can also let the browser handle the required field validation for you by adding "required" to the required fields. 您还可以通过在必填字段中添加“必填”,让浏览器为您处理必填字段。 Then you only have to handle the $.post() side of things. 然后,您只需要处理$ .post()方面。 However, this is not supported by all old browsers (eg IE8) so it's not guaranteed to stop the form from being submitted with empty values. 但是,并非所有旧版浏览器(例如IE8)都支持此功能,因此不能保证阻止表单以空值提交。

Eg: 例如:

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

And, of course, you will need to validate the input on the server side (PHP) as well. 并且,当然,您还需要在服务器端(PHP)上验证输入。

Add an ID to your form: 在表单中添加一个ID:

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

Now, instead of capturing the click event on #register , try to capture the submit event of the form . 现在,而不是捕捉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...
});

So your code will look like: 因此您的代码将如下所示:

HTML 的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 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.

相关问题 JS,只使用 html。 我可以检查用户浏览器吗? - JS, only use html. Can I check user browser? 如何获取值用户输入的html文本表单字段传递给javascript函数? - How to get value user entered into html text form field passed to javascript function? 如何检查用户是否尚未将数据输入表单(用于发送)? - How to check if the user has not entered the data to a form (befor sending)? 如何检查用户输入的文本是否包含Javascript中的http:// - How to Check if User entered text contains http:// in Javascript 用html替换文本。 jQuery的 - Replace text by html. Jquery 如何将用户输入的表单值从html传递给javascript? - How to pass a user entered form value from html to javascript? 如何计算用户在文本表单中输入的特定符号的数量 - How to count the amount of specifc symbols that a user has entered in a text form html 中有 reg no 和 full name 2 个表单字段。 当使用 Javascript 输入与名称关联的 reg 时,我想填写全名 - There are 2 form fields as reg no and full name in html. I want to fill full name when reg no associated with name is entered using Javascript Java脚本:onsubmit =“check_rfields();”在html的表单标记中。 但是验证失败了 - Java Script: onsubmit=“check_rfields();” in form tag of html. But getting failed in validation 使用用户输入的文本设置html元素的CSS - Setting the CSS of an html element with text entered by the user
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM