Mario
Mario

Reputation:

How can accept only number in input box

i have input box. i want to take only number in it even if user right click text and use mouse to paste.

I do not want plugin..just jquery code

i use keyup event but it no work

if user enter any other character except digit, it should instantly replace with empty string

Upvotes: 1

Views: 2089

Answers (4)

Alex Homm
Alex Homm

Reputation: 41

If you want to use a point use.

function numonly(root){
    var reet = root.value;   
    var arr1 = reet.length;   
    var ruut = reet.charAt(arr1-1);   
        if (reet.length > 0){   
        var regex = /[0-9]|\./;
                if (!ruut.match(regex)){   
            var reet = reet.slice(0, -1);   
            $(root).val(reet);   
            }   
        }   
    }
    //Then use the event handler onkeyup='numonly(this)'

Upvotes: 1

Michel
Michel

Reputation: 9440

What I should do is to check the input field when they are leaving the input field

so a jquery blur will do the job. or maybe a change event.

Upvotes: 3

Mottie
Mottie

Reputation: 86483

I don't know why you don't want a plugin, there are some very nice ones like this one. You can always add their code into your page instead of having a separate file.

Upvotes: 1

Juraj Blahunka
Juraj Blahunka

Reputation: 18553

<input type="text" name="test" id="test"  value="0" />

<script type="text/javascript">
$(function(){
    $("#test").keyup(function(){
        $(this).val( parseInt($(this).val()) );
    });
});

this will make your input to always contain numeric input

Upvotes: 0

Related Questions