Not receiving negative numbers in an input

Asked

Viewed 2,301 times

2

I have the following code: http://jsfiddle.net/ntywf/1987/

$(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 "-" signal. But always afterwards I can’t walk with the strokes to the left side, since the function keeps 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?

1 answer

2


What you can do is replace of your last character inserted, check if you have the 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>
<input type="text"/>

EDIT

I added in the code in case the user copies text to the input, where I check if the status of the input has changed with the change.

  • thanks <3 @Cesarmiguel

  • does not detect Ctrl+v or click and drag.. (believe me, there are people who click on a page and drag to another page’s input.. I do this) The safest way is to check the whole value of the input and pass a filter every time there is a focus on the input and to ensure more security, at the time of Submit do the check again.

  • Yes, that’s also true. I’ll change :P

Browser other questions tagged

You are not signed in. Login or sign up in order to post.