Gustavo Porto
Gustavo Porto

Reputation: 224

Automatic submit after type the last digit

I have a field 12345, I need submit a form automatic when I type the last digit, 5...

How can a do it with javascript?

Upvotes: 0

Views: 1055

Answers (6)

vonflow
vonflow

Reputation: 389

this solution assumes you have the maxlength attribute set accordingly. it also uses the 'input' event, which in my experience is far more reliable than keypress, keyup, etc.

html:

<form id="theform" action="gfdgf">
    <input id="someid" type="text" maxlength="5"/>
</form>​

jQuery:

$(document).on('input','#someid',function() {
    var that=$(this);
    if (that.val().length==that.attr('maxlength')) {
        that.closest('form').submit();
    }
});​

Fiddle

Upvotes: 1

Shmiddty
Shmiddty

Reputation: 13967

http://jsfiddle.net/3xHsn/

$("#foo").keyup(function(){
    var val = $(this).val();

    if (val.length == 5 && Number(val)){
        $("form").submit();
    }
});​

This will only submit if the value is 5 digits and is a valid number. An alternative would be to use regex to validate the value as a zipcode.

The regex solution can be found here: http://jsfiddle.net/3xHsn/1/

$("#foo").keyup(function(){
    var val = $(this).val();
    var regex = /^\d{5}$/;

    if (val.match(regex)){
        $("form").submit();
    }
});​

The regex is pretty simple here and only checks that the string is exactly five digits and only five digits.

Upvotes: 1

alexbusu
alexbusu

Reputation: 741

$('#input').keyup(function(){
    var content = new String( $(this).val() );
    if( content.length > 4 ){
        /* do your stuff here */
    }
});

Upvotes: 1

James
James

Reputation: 720

I saw someone created a jquery result but here is one in plain javascript

<input type="text" onkeyup="submitForm(this.value)">

function submitForm(str){
   if(str.length=5){
     document.forms["myform"].submit();
   }
}

Upvotes: 2

Alex Ball
Alex Ball

Reputation: 4474

Or this:

$('input[type=text]').on('keyup', function(){
    if($(this).val().length == 5){
        alert('5 digit!');
        //$('#myform').submit();
    }
});

Upvotes: 1

Andrelec1
Andrelec1

Reputation: 382

 $('.input').change(function() {
        if ($(this).val().length >= 5) {
            $('.Form').submit();
        }
    });

Upvotes: 1

Related Questions