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

5

18

Let's say I have a text field:

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

and I have some jQuery:

$(document).ready(function() {
    user = $("#username");

    user.submit(function() {

    })
})

I want to check if the length of the value entered in username is between 2 - 5 characters after I submit. If it's not then something happens.

I'm not too sure what I should be inside the user.submit(function(){}).

Southsoutheast answered 27/3, 2013 at 10:27 Comment(0)
I
47

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):

<!-- Fiddle: http://jsfiddle.net/ymdQq/ -->

<form id="myForm">
  Username: <input type="text" id="username" pattern=".{2,5}" required />
  <input type="submit" />
</form>
Insufficiency answered 27/3, 2013 at 10:31 Comment(0)
C
3

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')
} 
Compressibility answered 27/3, 2013 at 10:33 Comment(0)
B
3

$(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);
  });
});
<!-- Fiddle: http://jsfiddle.net/zoutepopcorns/b5Kqs/ -->

<form id="form" mehtod="POST" action="https://www.example.com">
  username: <input type="text" id="username" class="required" />
  <input type="submit" />
</form>

<div id="output"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Bengt answered 27/3, 2013 at 10:40 Comment(0)
I
1

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)
     {
     }
});
Insoluble answered 27/3, 2013 at 10:30 Comment(0)
S
0

you should try form validation for this kind of verification

Seaside answered 6/7, 2022 at 11:24 Comment(1)
Your answer could be improved by providing an example of the solution and how it helps the OP.Bernardina

© 2022 - 2024 — McMap. All rights reserved.