Operation in every browser the same way - javascript

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

Related

Prevent more than one space between words

I have a function that prevents people putting numbers or any symbol but letters onkeypress into a text box due to ongoing problems with data entry.
<td><input type="text" name="name" onkeypress="return isAlfa(event)"></td>
Now some staff for reasons unknown put two spaces between words at random times. So I need to prevent them putting more than one space between words. I want to do this in the same function, but it keeps breaking.
function isAlfa(evt) {
evt = (evt || window.event);
var charCode = (evt.which || evt.keyCode);
if ((charCode > 32)
&& (charCode < 65 || charCode > 90)
&& (charCode < 97 || charCode > 122)
) {
return false;
}
return true;
}
How can I prevent them entering more than one space between words?
Neglecting all the other helpful suggestions and comments and strictly following the OP's requirements one has to ...
Adapt the return condition in a way that takes into account if, with the current keystroke, a whitespace sequence is going to be created.
Thus one has to implement a method that determines exactly that.
There might be some possible helper methods too.
code example ...
function isWhiteSpace(char) {
return (/\s/).test(char);
}
function willCreateWhitespaceSequence(evt) {
var willCreateWSS = false;
if (isWhiteSpace(evt.key)) {
var elmInput = evt.currentTarget;
var content = elmInput.value;
var posStart = elmInput.selectionStart;
var posEnd = elmInput.selectionEnd;
willCreateWSS = (
isWhiteSpace(content[posStart - 1] || '')
|| isWhiteSpace(content[posEnd] || '')
);
}
return willCreateWSS;
}
function isAlfa(evt) {
evt = (evt || window.event);
var charCode = (evt.which || evt.keyCode);
return ((
(charCode > 32)
&& (charCode < 65 || charCode > 90)
&& (charCode < 97 || charCode > 122)
) || willCreateWhitespaceSequence(evt)) ? false : true;
}
<input type="text" name="name" onkeypress="return isAlfa(event)"/>
This code will prevent multiple white spaces, that is, it will only allow 1 space and it will prevent two or more white spaces. You can configure the amount of white space you want to deny. I am not the author of the original code, but I made the modifications to make it work properly.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Your-title</title>
<meta charset="utf-8">
</head>
<body>
<form>
<label>Name</label>
<input type="text" name="YourInputName">
</form>
</body>
</html>
<label>Name</label>
<input type="text" name="YourInputName">
<script>
var field = document.querySelector('[name="YourInputName"]');
field.addEventListener('keyup', function (event) {
var userName = field.value;
userName = userName.replace(/\s{2,}/g, ' ');
field.value = userName;
});
</script>
may be try to use something like this. on your keypress event try to check the last value by using string substr method and if that gives you a space and current code is also a Space then prevent or do whatever you want to do with input.
function checkstuff(event){
if (event.target.value.substr(-1) === ' ' && event.code === 'Space') {
console.log('space pressed in sequence');
}
}
<input type='text' onkeypress="checkstuff(event)">
Rather than listening for and evaluating each key press it would be far simpler just to react to any and all input and then sanitise whatever was entered via a RegExp.
Example:
<input type=text id=myfield />
JS:
document.querySelector('#myfield').addEventListener('input', evt => {
evt.target.value = evt.target.value.replace(/[^a-z\s]/ig, '').replace(/\s{2,}/g, ' ');
});
That first replaces all non-letters and spaces with nothing, then replaces sequences of 2 or more spaces with a single space.

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>

Ng-keypress prevent default for specific charCode

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.

input box taking numeric value in firefox

Using this code, user won't enter numeric value. In Google Chrome, input box is not taking numeric value but in Firefox it takes. I'm not getting, why it is happening. Any help appreciated.
<input type="text" name="station_name" id="station_name" onKeyPress="return noNumbers(this)" maxlength="45" />
this is my javascript function
<script type="text/javascript" language="javascript">
function noNumbers(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode;
if((charCode>=65 && charCode<=90)||(charCode>=97 && charCode<=122)||(charCode==32))
return true;
return false;
}
</script>
This is because, in Firefox, the event is passed as a parameter to the event handler. event property of the window object is IE only.
function enterHere(e)
{
e = e || window.event;
var code = e.keyCode || e.which;
if(code == 13)
find();
}
you are passing this in the following line, pass event
<input type="text" name="station_name" id="station_name" onKeyPress="return noNumbers(event)" maxlength="45" />
EDIT
ok try the follwoing function and the input tag as above:
function noNumbers(evt)
{
var charCode = evt.keyCode || evt.which;
if((charCode>=65 && charCode<=90)||(charCode>=97 && charCode<=122)||(charCode==32)||||(charCode==8))
return true;
return false;
}

Categories