如何检查文本框是否为空

How to check whether a text box is empty or not?

本文关键字:是否 文本 何检查 检查      更新时间:2023-09-26

我想检查文本框是否包含名称。如果没有,则应在按下提交按钮后弹出一条警告,显示一条消息,并且页面不应提交空白值。如果它包含值,那么应该提交该值。

我正在使用以下代码。当我将文本框留空并单击提交按钮时,它会按预期显示警报,但也会在解除警报后提交空值。

<html>
    <head>
        <script type="text/javascript">
            function check()
            {
                if (!frm1.FileName.value)
                {
                    alert ("Please Enter a File Name");
                    return (false);
                }
                return (true);
            }
        </script>
    </head>
    <body>
        <form name="frm1" id="frm1" action="/cgi-bin/page.pl" method="POST">
            <input type="text" name="FileName" id="FileName">       
            <input type="submit" value="send" name="btn_move" id="btn_move" onclick="check()">
        </form>
    </body>
</html>

代码中的问题是什么?

您需要执行onclick="return check();"

试试这个

<html>
    <head>
        <script type="text/javascript">
            function check()
            {
                if (document.getElementById('FileName').value==""
                 || document.getElementById('FileName').value==undefined)
                {
                    alert ("Please Enter a File Name");
                    return false;
                }
                return true;
            }
        </script>
    </head>
    <body>
        <form name="frm1" id="frm1" action="/cgi-bin/page.pl" method="POST">
            <input type="text" name="FileName" id="FileName">       
            <input type="submit" value="send" name="btn_move" id="btn_move" onclick="return check();">
        </form>
    </body>
</html>

您从check返回false,但您不是从事件处理程序返回值。

只有当事件处理程序返回false时,才会阻止默认操作(在这种情况下提交表单):

onclick="return check();"

在quicksmode.org上查看事件处理程序的精彩介绍,了解事件处理的基本知识(并了解比内联事件处理程序更好的方法)。


通常,最好不要在按下提交按钮时执行这些检查,而是在提交表单之前执行。因此,与其将处理程序绑定到按钮上的click事件,不如将其绑定到表单的submit活动,例如(使用传统的事件处理程序):

document.getElementById('frm1').onsubmit = function() {
    if (!this.FileName.value) {
        alert ("Please Enter a File Name");
        return false;
    }
};

优点是,将对所有表单提交进行检查,而不仅仅是在单击提交按钮时(例如,如果通过按enter键"执行"提交按钮)。