【问题标题】:jQuery cannot take the user input when the form is submitted提交表单时jQuery无法接受用户输入
【发布时间】:2013-08-15 03:03:56
【问题描述】:

我有以下代码。我需要在他提交表单时检查用户输入(他的电子邮件地址)的验证。如果电子邮件地址的格式不正确,则应显示错误消息。

问题是当我在文本框中输入错误的电子邮件地址并按下提交按钮时,没有任何反应。我曾经使用警报检查代码(我写了alert("Email"))并了解到$("#customerEmail").val() 没有返回值,而我目前在文本框中输入了一个值。可能是什么问题?

<form method="post" action="">
     <input type="text" id="customerEmail"/>
     <br/>
     <input type="submit" id="customerRegister" name="customerRegister"/>
</form>

<?php
  if(isset($_POST['customerRegister'])){
     echo'
    <script type="text/javascript" src="Scripts/jquery-1.10.2.min.js"></script>
    <script type="text/javascript">
       var EMail=$("#customerEmail").val();
       alert(Email);
       var atpos = EMail.indexOf("@");
       var dotpos = EMail.lastIndexOf(".");
           if (EMail != "")
       {
           if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= EMail.length) 
               {
                   $("#customerEmailSpan").html("wrong email address");
               }
           else if (atpos >= 1 && dotpos >= atpos + 2 && dotpos + 2 < EMail.length)
               document.getElementById("customerEmailSpan").innerHTML = "";
       }
    </script>';
    }
?>

【问题讨论】:

  • 为什么你不先用jquery检查,如果没问题,触发表单提交???
  • 附带说明您的 customerEmail 没有名称。
  • 您正在混合运行服务器端的 PHP 和运行客户端的 javascript。在您的脚本中,$("#customerEmail").val() 将始终为空,因为页面刚刚加载,每次您的 javascript 看到它时。
  • 我刚刚检查过了。不幸的是,我找到了第 n 个。
  • 试试 $(document).ready(function() { // 你的代码在这里;} 以及你的 jquery.js 的路径

标签: php jquery forms email submit


【解决方案1】:

你为什么不做这样的事情而不是混合js和php?

制作一个单独的javascript文件并将js代码放在这里。

您正在声明电子邮件并提醒电子邮件。这可能是一个原因。

(function($){

   //Call the script after document is loaded.
   $(document).ready(function() { 

      //on click event of submit button
      $("body").on("click", "#customerRegister", function(e){

       var EMail = $("#customerEmail").val();

       //This is the mistake you were doing. ie; print Email instead of EMail.
       alert(EMail);
       var atpos = EMail.indexOf("@");
       var dotpos = EMail.lastIndexOf(".");
           if (EMail != "")
       {
           if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= EMail.length) 
               {
                   $("#customerEmailSpan").html("wrong email address");
               }
           else if (atpos >= 1 && dotpos >= atpos + 2 && dotpos + 2 < EMail.length)
               $("#customerEmailSpan").val("");
       }


       });
    });

      }(jQuery));

【讨论】:

  • 谢谢桑德什。有效。但是你能解释更多吗?我把你的代码放在php标签中,我的问题就解决了。非常感谢您的帮助:)
  • 好的,我会在答案中添加解释。
  • 我在cmets中添加了一些解释
  • 抱歉,看来您的代码阻止了提交表单。您使用了 preventDefault(),这导致单击“customerRegister”不会提交表单,而是充当按钮!我需要“customerRegister”作为提交按钮并将表单内容发送到服务器。
  • 然后你可以删除 e.preventDefault();我已将其删除。
猜你喜欢
  • 1970-01-01
  • 2015-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多