Do not receive negative numbers in an input

2

I have the following code: link

$(document).ready(function () {    
$('input').keyup(function() {
        var $th = $(this).val();
        $th = $th.replace(/[-]/g, "");
        $(this).val($th)
        console.log( $(this).val());
    });
});

What I'm doing is removing the "-" sign. But always after I can not walk with the strokes to the left side, since the function is always sending the cursor to the end of the characters. How can I validate this without the cursor being sent to the end of the input?

    
asked by anonymous 29.06.2015 / 11:06

1 answer

2

What you can do is replace of your last entered character, check if you have KeyCode ( Link ) corresponding to" - "(which is 109), and replace:

$('input').keyup(function(e) {            
    var code = e.keyCode || e.which;
    if(code == 109 || code == 189) { //Enter keycode
       //Do something
        var valor = $(this).val();
        $(this).val(valor.replace(/[-]/g, ''))
    }
  });

$('input').change(function(e) {
   var valor = $(this).val();
   $(this).val(valor.replace(/[-]/g, ''))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><inputtype="text"/>

EDIT

I added in the code in case the user copied text to the input, where I check if the input state has changed with change .

    
29.06.2015 / 11:17