如何在 javascript 中强加一个必需的文本框

How to impose a required textbox in javascript

我的聊天有问题。 事实上,我有一个具有所需值的文本输入。 当我点击发送时,它 returns 为空而不是停止发送... 你能帮帮我吗?

<script>
    $("#submitmsg").click(function() {
        var clientmsg = $("#usermsg").val();
        $.post("chat-post.php", {
            text: clientmsg
        }); 

$("#usermsg").attr('required', true);

        loadLog;
        return false;
    });
</script>

基本上,如果该消息输入的值为空,您需要在发送 post 请求之前添加一个条件。请检查以下内容:

    <script>
        $("#submitmsg").click(function() {
            var clientmsg = $("#usermsg").val();

// This is the additional condition
            if(clientmsg != '' || clientmsg != null){

                $.post("chat-post.php", {
                    text: clientmsg
                }); 
            }
            else{
                alert('Please enter the message!');
            }

    $("#usermsg").attr('required', true);

            loadLog;
            return false;
        });
    </script>

您可以像这样验证输入字符串 if(clientmsg.trim())。最好在 html 代码中添加 required=true

 <input type='text' required="true">

并与 trim() 一起使用,它们将从字符串

中删除不需要的 space
<script>
    $("#submitmsg").click(function() {
        var clientmsg = $("#usermsg").val();
        if(clientmsg.trim()){
        $.post("chat-post.php", {
            text: clientmsg
        }); 
        loadLog;
        }
        return false;
    });
</script>

为了使必需的属性起作用,您需要在表单中输入。

<form>
  <input required type="text" />
</form>

我认为根本不需要每次点击按钮时都设置required属性。您只需要做一次,那么为什么不直接在 html?

中添加所需的属性呢?

即使您不想在 HTML 中添加它,也只需添加一次即可。

<script>
  $("#usermsg").attr('required', true); // Add the attribute required to the input

  // Do the AJAX function after you submit the form.
  // Before submitting, it will have to be validated, so you don't even have to validate it in JS. Just native HTML5
      $("form").submit(function() {
        // do the rest here
      }
    </script>