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

时间:2017-05-03 14:09:54

标签: javascript required

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

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

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

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

3 个答案:

答案 0 :(得分:0)

基本上,如果该消息输入的值为空,则需要在发送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>

答案 1 :(得分:0)

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

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

trim()一起使用时,他们会从字符串

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

答案 2 :(得分:0)

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

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

我认为每次单击按钮时都不需要设置必需的属性。您只需要执行一次,那么为什么不在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>