Ng-keypress prevent default for specific charCode - javascript

I have an input that is type="number". I want to prevent the user from typing decimals, addition, subtraction, or e into the input. Currently I am trying to e.preventDefault() on ng-keypress to disable the key completely. But it is not working. I am using typescript and angularJs. It is seeing the event on keypress but it is not preventing the entry from being made. Or, would using ng-pattern with a regex be an alternative option retrict input to 0-9?
setCapacityType(e) {
let keyCode = (e.keyCode ? e.keyCode : e.which);
if (keyCode < 48 && keyCode > 57) {
e.preventDefault();
console.log("xx");
}
}
<input type="number" ng-keydown="vm.setCapacityType($event)"
autocomplete="off" autocorrect="off" spellcheck="false">

Well, two things:
First, you have to instantiate your function:
vm.setCapacityType = function(e) {
To allows only numbers [0-9] you should write your condition as below:
if (keyCode < 48 || keyCode > 57) {
Now, you can have something like this:
angular.module('app', [])
.controller('mainCtrl', function() {
var vm = this;
vm.setCapacityType = function(e) {
let keyCode = (e.keyCode ? e.keyCode : e.which);
if (keyCode < 48 || keyCode > 57) {
console.log("Prevent!");
e.preventDefault();
}
}
});
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>
<body ng-controller="mainCtrl as main">
<input type="text" ng-keydown="main.setCapacityType($event)" autocomplete="off" autocorrect="off" spellcheck="false">
</body>
</html>
ng-pattern with a regex be an alternative option retrict input to 0-9?
No, ngPattern directive doesn't prevent/restrict the input.

Related

Operation in every browser the same way

I have problem. This code works well only in Google Chrome. I need it to work well in any other browser. Does anyone know how to do it and help me? I need the code to work well in firefox. Because when you open a script in the Firefox browser, the key (TAB) is detected as a letter. and I can not freely switch between columns
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript" ></script>
<meta charset="utf-8">
</head>
<body>
<script type="text/javascript" >
function preventNonNumericalInput(e){var n=void 0===(e=e||window.event).which?e.keyCode:e.which;String.fromCharCode(n).match(/^[0-9,\b,-]+$/)||(alert("WPISZ LICZBĘ"),e.preventDefault())}!function(n){n.fn.average=function(){var e=0;return this.each(function(){e+=parseFloat(n(this).val())}),e/n(this).length}}(jQuery),$(document).ready(function(){$(":reset")}),$(document).ready(function(){$("#calc").click(function(){var e=$("input[type='number']").average();console.debug(e),$("#result").html(e)}),$(".reset").on("click",function(){$("#result").html(" ")})});
</script>
<h1>Oblicz średnią:</h1>
<form action="">
<input onkeypress="preventNonNumericalInput(event)" type="number">
<input onkeypress="preventNonNumericalInput(event)" type="number">
<input onkeypress="preventNonNumericalInput(event)" type="number">
<div id="result" type="reset" ></div><br>
<input type="button" id="calc" value="Licz">
<input type="reset" value="Reset" class="reset">
</form>
</body>
</html>
So, you've put a bit of Javascript to disallow the user to use anything else than numerical inputs into the form, right ? Hence pressing any other key than the 0-9 one while in the input launch your alert : "WPISZ LICZBĘ".
First of all, you want to "unminify" your unreadable Javascript line.
function preventNonNumericalInput(e) {
var n = void 0 === (e = e || window.event).which ? e.keyCode : e.which;
String.fromCharCode(n).match(/^[0-9,\b,-]+$/) || (alert("WPISZ LICZBĘ"), e.preventDefault())
}! function(n) {
n.fn.average = function() {
var e = 0;
return this.each(function() {
e += parseFloat(n(this).val())
}), e / n(this).length
}
}(jQuery), $(document).ready(function() {
$(":reset")
}), $(document).ready(function() {
$("#calc").click(function() {
var e = $("input[type='number']").average();
console.debug(e), $("#result").html(e)
}), $(".reset").on("click", function() {
$("#result").html(" ")
})
});
This line :
String.fromCharCode(n).match(/^[0-9,\b,-]+$/) || (alert("WPISZ LICZBĘ"), e.preventDefault())
Reads the input and sees if it is a number (0-9) or an hyphen. If you add || e.keyCode == 9 it lets you use the tab button.
String.fromCharCode(n).match(/^[0-9,\b,-]+$/) || e.keyCode == 9|| (alert("WPISZ LICZBĘ"), e.preventDefault())
But you'll still have problem, like in Chrome you can use up and down arrows to increase or decrease the amount, while in Firefox this gives you an error.
Try this
function preventNonNumericalInput(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
JSFiddle for reference

Accept Number Special Character and Comma in Input field using Charcode

I am using charcode so that user can input only number, special-character and comma.
<input type="text" class="form-control numOnly"
onkeypress="return event.charCode >= 48 && event.charCode <= 57">
Right now it is accepting only number but I want to allow special character and comma using charcode.
what am I missing?
Try Below
<input type="text" class="form-control numOnly" onkeypress="return event.charCode >= 32 && event.charCode <= 57">
<input type="text" class="form-control numOnly" onkeypress="return Validate(event);">
<script type="text/javascript">
function Validate(event) {
var regex = new RegExp("^[0-9-!##$%*?,]");
var key = String.fromCharCode(event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
}
</script>
Here you can view all the javascript charcodes.
https://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
The comma one for example is 188.
You can also use https://github.com/KevinSheedy/jquery.alphanum to facilitate your life.
Edit: I noticed you have a class named NumOnly there. Is it only for styling?

Masking to input type text to only 4 digits

I am trying restrict a user from entering more than 4 digits.
For that I am using:
$("#YEAR").mask("(9999)");
But I'm getting the following error:
JavaScript runtime error: Object doesn't support property or method 'mask'
Do I need to include a library for it?
A simple solution could be:
$(function () {
$('#YEAR').on('keypress', function(e) {
var charCode = (e.which) ? e.which : event.keyCode
if (charCode < 48 || charCode > 57) {
return false;
}
return true;
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" maxlength="4" id="YEAR" name="YEAR"/>
</form>

How to alert user that input type text detects a dot when user input?

I have this html and jquery code that alerts the user to have numbers only to input.
I want to alert the user when user inputs a dot '.' in the text field.
<html>
<body>
<div class="form-group" id="parentID">
<input class="form-control" placeholder="ID Number (10 max numbers)" id="childID" name="idnumber" type="text" maxlength="10" required autofocus>
<span id="checkID"></span>
</div>
</body>
<script>
var ID = $("#childID").val();
if (ID.indexOf(".") != -1) {
$("#checkID").html("ID number must contain numbers only");
$("#checkID").css("color", "orange");
}
$(document).ready(function() {
$("#childID").keyup(checkPasswordMatch);
});
//In this function it will disable special characters in user input but still accepts the '.' and '>' character type, what keycode is it to disable that 2 character?
$(function() {
$('#parentID').on('keydown', '#childID', function(e) {-1 !== $.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) || /65|67|86|88/.test(e.keyCode) && (!0 === e.ctrlKey || !0 === e.metaKey) || 35 <= e.keyCode && 40 >= e.keyCode || (e.shiftKey || 48 > e.keyCode || 57 < e.keyCode) && (96 > e.keyCode || 105 < e.keyCode) && e.preventDefault() });
})
</script>
</html>
I want the span id="checkID" to appear when the input field detects a dot on keyup. I tried using indexOf() but the span tag won't appear. Can anyone help me?
I have updated your code in fiddle. Please find the updated code in below fiddle link. Just added one function and updated keyup and keypress events.
$(function() {
$('#parentID').on('keypress keyup', '#childID', function(e) {
if(isNumber(e)){
$("#checkID").html("");
} else{
//e.preventDefault();
$("#checkID").html("ID number must contain numbers only");
$("#checkID").css("color", "orange");
}
});
});
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode <= 46 || charCode > 57)) {
return false;
}
return true;
}
See the Demo
It shows the error message. If you don't want to allow other characters please uncomment //e.preventDefault();
try this this check it real time
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<style type="text/css">
</style>
<body>
first name :<input type="text" name="firstname" class="tfield" id="myinput">
</body>
<script type="text/javascript">
$(document).ready(function(){
$("#myinput").on('change keyup keydown',function(){
var thetext = $(this).val();
if (thetext.indexOf('.') != -1)
{
alert("contains dot sign")
}
else
{
//no need
}
});
});
</script>
$("#childID").keyup(function(){
if ($("#childID").val().indexOf('.') > -1) {
alert('dot');
}
});
Working Demo 1
Working Demo 2
Just write one javascript function which will check the charCode. The keyCode for dot is 46. so javascript function may like this
$('#childID').keypress(function (e) {
//if the letter is dot
if (e.which == 46) {
//display alert error message
alert("you cant enter dot");
$(this).focus();
return false;
}
});
This will not let the user type dot in the text field.
Demo:
<!DOCTYPE html>
<html>
<title></title>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<style type="text/css">
</style>
<body>
Enter text :<input type="text" name="childID" id="childID">
</body>
<script type="text/javascript">
$(document).ready(function(){
$('#childID').keypress(function (e) {
//if the letter is dot
if (e.which == 46) {
//display alert error message
alert("you cant enter dot");
$(this).focus();
return false;
}
});
});
</script>

How can i change the textbox value on pressing space?

I want to change the English words into Hindi
every time I press space in textbox its a keypress event but how to apply only for space key.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#textboxid').keypress(function(e){
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 32) { //space keycode
//Do language transilation here
}
});
});
</script>
<form id="form1" name="form1">
<input type="text" name="textfield" id="textboxid" />
</form>
Space is 32. So using jQuery keypress event you can do it with:
$("textarea").on("keypress", function(e) {
if (e.keyCode == 32) {
// ...
}
});
For a vanilla js answer:
document.getElementById( 'textboxid' ).onkeypress = function( e ) {
if ( e.keyCode === 32 ) {
// Translate into Hindi
}
}

Categories