0

I need a field which can only take numbers, but not allow for signs such as "+", "-", "*" and "/". 0 can also not be the first number. If I make an Input field and set it's type to "number" I'm still allowed to write at least "+" and "-", and I can't quite seem to prevent the user from writing 0 as the first number either.

$('input#update-private-ext').on('keydown', function (e) {
    var value = String.fromCharCode(e.keyCode);
    if ($(this).text.length == 0 && value == 0) {
        return false;
    }
});

The above was my first attempt at making the function disallow 0 as the first character, but it doesn't seem to work. It just lets me write 0 as the first character. I also tried this to stop the signs from showing up:

$('input#update-private-ext').on('keydown', function (e) {
    var badChars = '+-/*';
    var value = String.fromCharCode(e.keyCode);
    if ($(this).text.length == 0 && value == 0) {
        return false;
    }
    if (badChars.indexOf(value) == -1) {
        return false;
    }
});

But with the badChars check, I cannot write anything in my field. So what am I missing here?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
OmniOwl
  • 5,477
  • 17
  • 67
  • 116

3 Answers3

1

You should use e.key to get the current key pressed. String.fromCharCode(e.keyCode) gives the wrong result.

Also you should check if the bad chars is not -1. If it is, then your char is not a bad character and so you should not enter the if.

If you want to get the length of the input field you should use jQuery's .val() and not .text(). Or you can simply do it without jQuery using this.value.length.

$('input#update-private-ext').on('keydown', function (e) {
        var badChars = '+-/*';
        var value = e.key;
        if (this.value.length == 0 && value == '0') {
            return false;
        }

        if (badChars.indexOf(value) !== -1) {
            return false;
        }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="update-private-ext">
Ivar
  • 6,138
  • 12
  • 49
  • 61
1

When you compare numbers and strings you must remember that numbers are encoded by using character codes from 48 to 57 and comparing strings with numbers is error-prone in JavaScript as there are many implicit coercions. You should be comparing objects of the same type to avoid the confusion.

In your case, the comparison should be done in the way that parsed string from the String.fromCharCode equals '0' - zero character (string), not the 0 as a number.

There are also issues of the keyCode parsing which yield strange values for the symbols because you would have to manually consider if Shift and other meta keys are pressed when parsing. Save yourself a trouble and just use e.key to get parsed key value.

By the way, please see the difference between this and $(this). Basically, in your case, it means that real instance of the input field is the first element of JQuery iterator - $(this)[0]. You may then just use this, which is automatically set to the target element in the event handler.

Please see the following example of blocking first 0 with debug information printed out:

$('input#update-private-ext').on('keydown', function (e) {
    var value = e.key;
    
    console.log('Typed character:');
    console.log(value);
    
    console.log('$(this)');
    console.log($(this));
    
    console.log('this (input element):');
    console.log(this);
    
    console.log("input's value:");
    console.log(this.value);
    
    if (this.value.length == 0 && value == '0') {
        console.log('blocked');    
        return false;
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="update-private-ext" />

In order to block other characters you can just filter them the following way (remember that indexOf returns -1 when the index is not found):

$('input#update-private-ext').on('keydown', function (e) {
    var badChars = '+-/*';
    var value = e.key;
    if (this.value.length == 0 && value == '0') {
        return false;
    }
    //Please note NOT EQUALS TO -1 which means not found.
    if (badChars.indexOf(value) !== -1) {
        return false;
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="update-private-ext" />
Community
  • 1
  • 1
Przemysław Zalewski
  • 3,836
  • 1
  • 23
  • 23
0

You can do something like this below:
1. Check for bad chars if badChars.indexOf(v) >= 0.
2. Disallow starting from 0 by checking if the input starts from 0 and if yes, set the input field to blank.

This can give you a start!

$('input#update-private-ext').on('keydown', function(e) {
  var badChars = '+-/*';
  var v = e.key;
  if (badChars.indexOf(v) >= 0) {
    return false;
  }
  if ($(this).val().startsWith('0')) {
    $(this).val("");
    return false;
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="update-private-ext" />
Pankaj Shukla
  • 2,657
  • 2
  • 11
  • 18