tags:

views:

298

answers:

4

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

+3  A: 

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.

michel
For simplicity, this is the best option. If you want full control, you'd instead prevent default action on keydown/keypress for any undesired key combinations (which becomes fairly complex to do right and keep expected behavior...), and the ability to preserve the caret placement whenever filtering non-numeric characters for other events (like paste).
eyelidlessness
A: 
<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

Juraj Blahunka
this not work when user right click textbox and paste nondigit
Mario
have you tried it?for me just works fine, even when pasting
Juraj Blahunka
yes i try..your code not work..try this step..when page load, use mouse to right click on input and paste nondigit..it accepts
Mario
This will also create havoc for caret placement.
eyelidlessness
trigger your listener in the end, this will prevent inserting on page load, like this:$("#test").keyup(function(){ $(this).val( parseInt($(this).val()) ); }).keyup();
Shein Alexey
+1  A: 

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.

fudgey
Plus, jQuery plugins **are** jQuery code.
ceejayoz
A: 

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)'
Alex Homm