Shawn
Shawn

Reputation: 3149

html input - numbers only AND overwrite mode

I have HTML input fields that need to limit the input to numbers only as well as set the field to overwrite mode (text is highlighted) when the user clicks or tabs over to the field.

I seem to be able to do one or the other, but not both at the same time.

<input type="text" class="numOnly" value="10"> 
    <input type="text" class="numOnly" value="20"> 
        <input type="text" class="numOnly" value="30"> 
            <input type="text" class="numOnly" value="40"> 
<input type="text" class="numOnly" value="50"> 
    <input type="text" class="numOnly" value="60"> 
        <input type="text" class="numOnly" value="70"> 
            <input type="text" class="numOnly" value="80">   

$('.jqndo').keyup(function () {
    this.value = this.value.replace(/[^0-9\.-]/gi, "");
});

$(".jqndo").focusin(function(){
    $(this).select();
}); 

What happens is a preliminary set of numbers is entered, then later someone goes back in and corrects them. It would nice if they could just tab across and enter the new numbers without highlighting first.

JSfiddle

Upvotes: 0

Views: 2431

Answers (2)

Pawan Samdani
Pawan Samdani

Reputation: 1624

You should use type="number" in all the input tags that you want numbered.

And to deny non-number characters use :

$(".numOnly").keypress(function(key){
    if(key.charCode < 48 || key.charCode > 57) return false;
});

instead of

$(".numOnly").keyup(function () {
    this.value = this.value.replace(/[^0-9\.-]/g, "");
});

Fiddle link

Reference : http://www.webdesignerdepot.com/2012/10/restricting-input-with-jquery/

Upvotes: 1

sergioFC
sergioFC

Reputation: 6016

You could use oninput and onfocus events:

$(".numOnly").on('input',function () {
    this.value = this.value.replace(/[^0-9\.-]/g, "");
});

$(".numOnly").on('focus', function(){
    $(this).select();
});    

Upvotes: 0

Related Questions