Touchscreen Keyboard - Limit the number of characters entered in javascript

Asked

Viewed 38 times

1

I’m working on a touchscreen keyboard, put the numbers from 0 to 9, clear key and enter. As the numbers are clicked they appear in a display.

To capture the clicked numbers I am using the following function:

function addNumber(e){
    var v = $( "#PINbox" ).val();
    $( "#PINbox" ).val( v + e.value );
}

How do I limit the amount of captured numbers by 5? Ex.: 12345 and no more numbers accepted.

Thanks in advance for your attention.

2 answers

2

You can check whether the field already contains the character limit defined at each iteration.

function addNumber(e){
    var v = $( "#PINbox" ).val();
    if( v.length < 5 )
        $( "#PINbox" ).val( v + e.value );
}

If you’re working with HTML can also try to set a range for the field (not sure it will work in this case). So you can add an attribute max which will specify as many as possible that you can enter.

<input type="number" max="99999" />

If you add a max and a min, may specify the permitted range of values:

<input type="number" min="1" max="99999" />
  • 2

    The <= is incorrect. It should just be <, otherwise it will accept 6 characters.

  • True @Sam, corrected the reply.

  • Dude, you don’t even need the else return false... only the if already resolves.

0


One way is to use one ternary operator in the .val(). If the number of characters is less than 5, it will concatenate the current value + the number clicked, otherwise it will keep the 5 numbers reached:

function addNumber(e){
   var v = $( "#PINbox" ).val();
   $( "#PINbox" ).val( v.length < 5 ? v + e.value : v );
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="PINbox" type="text" readonly>
<br><br>
<button value="1" onClick="addNumber(this)">1</button>
<button value="2" onClick="addNumber(this)">2</button>
<button value="3" onClick="addNumber(this)">3</button>
<button value="4" onClick="addNumber(this)">4</button>
<button value="5" onClick="addNumber(this)">5</button>
<button value="6" onClick="addNumber(this)">6</button>
<button value="7" onClick="addNumber(this)">7</button>
<button value="8" onClick="addNumber(this)">8</button>
<button value="9" onClick="addNumber(this)">9</button>
<button value="0" onClick="addNumber(this)">0</button>
<br><br>
<button onClick="$('#PINbox').val('')">Limpar</button>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.