How to use jQuery to onsubmit and check if the value is 2 - 5 characters?

后端 未结 4 1887
走了就别回头了
走了就别回头了 2020-12-15 21:59

Let\'s say I have a text field:

Username: 

相关标签:
4条回答
  • 2020-12-15 22:16

    I made a Fiddle

    You can use a statement as

    $(document).ready(function(){  
        $("#form").submit(function(e) {
           length = $("#username").val().length;
           if((length > 2 && length < 5)) {
               $("#output").html("correct, logging in");
           } else {
               $("#output").html("incorrect, must have 3 or 4 chars");
           }
           return (length > 2 && length < 5);
        });
    });
    

    And HTML

    <form id="form" method="POST" action="http://www.cnn.com">
    username: <input type="text" id="username" class="required" />
    <input type="submit" />
    

    0 讨论(0)
  • 2020-12-15 22:22

    First you'll need an actual form:

    <form id="myForm">
        Username: <input type="text" id="username" class="required" />
        <input type="submit" />
    </form>
    

    then:

    $(document).ready(function(){
        $('#myForm').on('submit', function(e){
            e.preventDefault();
            var len = $('#username').val().length;
            if (len < 6 && len > 1) {
                this.submit();
            }
        });
    });
    

    Or in HTML5 you can use the pattern attribute (not supported in Safari and IE9-and below):

    <form id="myForm">
        Username: <input type="text" id="username" pattern=".{2,5}" required />
        <input type="submit" />
    </form>
    

    FIDDLE

    0 讨论(0)
  • 2020-12-15 22:22

    Bind submit to form instead of input type text and check its value in submit event. It would be better to assign some id to form and use form id selector to bind submit.

    $('form').submit(function(){
          username = $('#username').val();
         if(username.length > 1 && username.length < 6)
         {
         }
    });
    
    0 讨论(0)
  • 2020-12-15 22:23

    You can check the value of the input field with user.val() and the length of the string with user.val().length.

    That way you can do something like this:

    if(user.val().length < 2 || user.val().length > 5) {
        console.log('test')
    } 
    
    0 讨论(0)
提交回复
热议问题