Leorah Sumarong
Leorah Sumarong

Reputation: 127

How to set limit and character length in input type number?

I have this JavaScript code that sets the range value from 1-5.

$(document).on('keyup','#getScore',function(){
    var a = $(this).attr('value');
    if($(this).val() > 5 ){
        $(this).val(a);
    }
})

Now I also want to set the number of digits to 1. How can I do that?

Upvotes: 0

Views: 824

Answers (6)

prasanth
prasanth

Reputation: 22510

Set with min and max value attribute and find the value length greater then one .apply % 10 %5 its with convert to 1-5 .surely never exist 2 digit not go with above 5 . And user for a% 10 % 5 == 0 ? 1 : a% 10 % 5 ternary operator its control with 1-5

$(document).on('keyup','#getScore',function(){
    var a = $(this).val()
    if($(this).val().length > 1 ){
      a = a < 0 ? a*-1 : a; //for negative number 
            $(this).val(a% 10 % 5 == 0 ? 1 : a% 10 % 5);
    }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input  id="getScore" type="number" min="0" max="5">

Upvotes: 0

trincot
trincot

Reputation: 351393

I would do this, trying to get a correct digit from the input or else putting a valid one instead:

$(document).on('input','#getScore',function(){
    var a = $(this).val();
    if (a.length > 1)
        a = a.replace(/[^1-5]/g, '').substr(-1);
    $(this).val(a > 5 ? 5 : a < 1 ? 1 : a);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="getScore">

Upvotes: 1

johngeorgewright
johngeorgewright

Reputation: 1005

Just out of curiosity, if you're trying to restrict an input between the numbers 1-5, why not just use a number input?

<form>
  Quantity (between 1 and 5):
  <input type="number" name="quantity" min="1" max="5">
</form>

Upvotes: 0

Mohideen bin Mohammed
Mohideen bin Mohammed

Reputation: 20206

if your value is integer means, val.length need to be string.. use .toString() before getting length.

$(document).on('keyup','#getScore',function(){
    var a = $(this).attr('value');
    if($(this).val() > 5 && $(this).val().toString().length > 1 ){
        $(this).val(a);
    }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

Upvotes: 0

Raspberryano
Raspberryano

Reputation: 159

Add if ($(this).val().length > 1)

Upvotes: 0

imskm
imskm

Reputation: 805

Try this

    $(document).on('keyup','#getScore',function(){ 
    var a = $(this).val(); 
    if(a.length> 1 &&  $(this).val() > 5) {   
 // Your code
     }
     })

Upvotes: 0

Related Questions