Search code examples
javascriptrequired

How to impose a required textbox in javascript


I have a problem with my chat. Indeed, I have a text input with the required value. When I click on Send, it returns empty instead of stopped sending... Can you help me please ?

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

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

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

Solution

  • you could validate the input string like this if(clientmsg.trim()) .Better add the required=true in your html code

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

    And use with trim() they will remove the unwanted space from string

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