【问题标题】:Check textbox before submitting提交前检查文本框
【发布时间】:2013-04-14 09:34:25
【问题描述】:

如何在提交前检查文本框?

<form action='search.php' method='GET'>

         <input type="text" id= "q" name="q" class='textbox' >

         <input type="submit" id='submit' value="Search" class ='button' >

     </form>

【问题讨论】:

    标签: javascript html search


    【解决方案1】:

    用 JavaScript 验证试试这个简单的方法:

    <html>
        <head>
            <script type="text/javascript">
                function check()
                {
                    var searchtext = document.getElementById("q").value;
                    if(searchtext=='')
                    {
                        alert('Enter any character');
                        return false;
                    }
                }
            </script>
        </head>
        <body>
            <form  action='search.php' method='GET' onSubmit="return check();">
                <input type="text" id= "q" name="q" class='textbox' >
                <input type="submit" id='submit' value="Search" class ='button' >
            </form>
        </body>
    </html>
    

    【讨论】:

    • form标签的action属性表示他需要用PHP进行验证
    • 哦,好的。抱歉,以为您在提交期间进行了验证。使用 PHP 验证仍然是一个好主意,因为它正在运行 PHP 脚本
    【解决方案2】:
    <?php
    if(!empty($_GET['q']))
    {
    //if it is not empty, do something
    }
    else
    {
    //otherwise do this
    }
    ?>
    

    如果您要从表单发送内容,我还建议您使用 POST 而不是 GET。

    【讨论】:

      【解决方案3】:

      您可以使用jQuery,如下所示:

      $(function(){
          $('#submit').click(function(e){
              if($('#q').val() != null && $('#q').val().length > 0){
                  $.get('search.php', $('#formId').serialize(), function(result){});
              }
              else{
                  //Otherwise do this
              }
              e.preventDefault();
          });
      });
      

      【讨论】:

      • 这对于简单的验证来说相当复杂
      • 你有更简单的解决方案吗?
      • 你不需要使用jquery,他需要做的事情相当复杂
      【解决方案4】:

      您可以使用一些时尚的 jQuery 库来轻松编码,例如 jQuery validation plugin

      【讨论】:

      • 谢谢,我不喜欢使用 jquery,因为它会导致性能问题
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-19
      • 2015-11-07
      • 1970-01-01
      • 2016-04-06
      • 2011-10-07
      • 2022-11-24
      • 1970-01-01
      相关资源
      最近更新 更多