0

I have a input element and want to make sure that only numeric values are allowed. I found a working example here.

Now I want to get the value of this field and write it into an other input element:

$(".firstinput").keydown(function (e) {
    // Allow: backspace, delete, tab, escape, enter and .
    if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
         // Allow: Ctrl+A, Command+A
        (e.keyCode == 65 && ( e.ctrlKey === true || e.metaKey === true ) ) || 
         // Allow: home, end, left, right, down, up
        (e.keyCode >= 35 && e.keyCode <= 40)) {
             var $this = $(this).val();
             $("copiedinput").val($this);
             return;
    }
    // Ensure that it is a number and stop the keypress
    if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
        e.preventDefault();
    }
});

This almost works but I do only get the value after pressing enter or backspace. Typing in '222' and backspace leads to '22' for the .firstinput and '222' for the .copiedinput. How can I get the live value?

Community
  • 1
  • 1
hes
  • 121
  • 2
  • 14

1 Answers1

0

Try this:

$(".firstinput").keyup(function() {
    $(".firstinput,.copiedinput").val($(this).val().replace(/[^\/\d]/g, ""));
});

Or handling keydown:

$(".firstinput").keydown(function(e) {
    return (
        $.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
        (e.keyCode == 65 && (e.ctrlKey === true || e.metaKey === true)) || 
        (e.keyCode >= 35 && e.keyCode <= 40) ||
        (e.keyCode >= 96 && e.keyCode <= 105) ||
        (!e.shiftKey && e.keyCode >= 48 && e.keyCode <= 57)
    );
}).keyup(function() {
    $(".copiedinput").val($(this).val());
});
Vagharsh
  • 396
  • 1
  • 6