if input has reached 7 digits, stop the function

924 views Asked by At

So basically I have a button .button, which adds a number to my input #number everytime it's pressed. Now, when I already have 7 digits in my input #number, I want the function to like 'stop working'.

Here is my code (works fine):

  function nrtwo(hello){
            var das = $(hello).html();
            var tempNum = $("#number").val();
            $("#number").val(tempNum + '' + das);
            tempNum = null;
        };

        $(".button").click(function(){
            nrtwo(this);
        });

I was thinking of something like this?

if ($("#number").attr('maxlength') == '7') {
                return false;
            }

Thanks for the help.

5

There are 5 answers

2
Faouzi Oudouh On BEST ANSWER

Try this .length it is a Number and unblind click event when you reach 7 digits :

Working jsFiddle

$(".button").click(function(){

 if ($("#number").val().length == 7) {
     $(this).unbind('click');
     return false;
 }else{
     nrtwo(this);
 }

});
0
Mihai Alexandru-Ionut On

One method is to use .length property. Please try this:

if ($("#number").val().length == '7') {
     return false;
}

$('#add').click(function() {
  if ($("input").val().length != '7') {
     $('input').val(parseInt($('input').val())+1);
   }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" value="999998"/>
<button type="button" id="add">Add</button>

0
31piy On

You need to handle this scenario in the click event itself. Please see the following example:

$(".button").click(function(){
  if ($("#number").val().length <= 7) {
    nrtwo(this);
  }
});

This will only call the nrtwo method only when the input's length is less than or equals to 7.

0
cringe On

If you are handling numbers only, you can also check the numeric value before adding to it.

$('#add').click(function() {
  var value = parseInt($('#output').val());
  if(value <= 999999) {
    $('#output').val(value + 1);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="add">Add</button>
<input type="text" id="output" value="999995" />

1
Maths RkBala On

$('#number').keypress(function(event){
        var n = $(this).val();
        if(n.length == 7){
            event.preventDefault(); //stop character from entering input
        }
       if(event.which != 8 && isNaN(String.fromCharCode(event.which))){
           event.preventDefault(); //stop character from entering input
       }

   });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<input id="number"/>