JS - Why isnt the second value in my "or" equation recognised - javascript

im trying to create a function that will move an png image either up, down, left or right by the user either pressing WASD or the Arrow Keys. At the moment i have figured out a way to move the item using WASD however when i introduce the "or" operand and use the Key.Code for the arrow keys the arrow keys aren't recognised even though it will still recognise WASD
<body>
<div class="scene">
<div class="rocket">
<img src="rocket.png" alt="" />
</div>
</div>
<script src="script.js"></script>
document.addEventListener("keydown", (e) => {
var rocket = document.querySelector(".rocket");
let speed = 10;
if (event.keyCode == (87 || 38) && rocket.offsetTop > 100) {
rocket.style.top = `${rocket.offsetTop - speed}px`;
}
if (event.key == "s" && rocket.offsetTop < window.innerHeight - 300) {
rocket.style.top = `${rocket.offsetTop + speed}px`;
}
if (event.key == "a" && rocket.offsetLeft > 50) {
rocket.style.left = `${rocket.offsetLeft - speed}px`;
}
if (event.key == "d" && rocket.offsetLeft < window.innerWidth - 125) {
rocket.style.left = `${rocket.offsetLeft + speed}px`;
}
if (event.key == " " && rocket.offsetTop > 100) {
rocket.style.top = `${rocket.offsetTop - 200}px`;
}
console.log(event.keyCode);
});

This expression:
87 || 38
Evaluates to 87. Every time. Which means this expression:
event.keyCode == (87 || 38)
Compares the value to 87. Every time.
Don't think of these logical conditions as intuitive human language. They need to be built as individual logical expressions which individually evaluate to a value. What you're looking for is this:
(event.keyCode == 87 || event.keyCode == 38)

You should try
if ((event.keyCode == 87 || event.keyCode == 38) && rocket.offsetTop > 100)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR

Related

Javascript Validation not working on Mobile

I have used some javascript for validation eg. allow only numbers or text, restrict length.it's working fine on desktop but on mobile below mention javascript is not working.
/// allow numbers only
$('#pincode, #billing_phone').keypress(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
//display error message
return false;
}
});
//allow characters only
$(function() {
$("#billing_first_name, #billing_last_name").keydown(function(e) {
if ( e.which != 9) {
var key = e.keyCode;
if (!((key == 8) || (key == 32) || (key == 46) || (key >= 35 && key <= 40) || (key >= 65 && key <= 90))) {
e.preventDefault();
}
}
});
});
// restrict length
$("#reg_billing_city").attr('maxlength',30);
$("#billing_phone, #reg_billing_phone, .qty").attr('maxlength',10);
What I have Tried:
I have written my javascript according to screen width like this
if (screen.width < 600) {// javascript goes here }
and it's working fine on desktop but on mobile, it's not working.
Can you please help to identify the problem?

how to prevent "shift+greater than" being typed in Javascript

I have a requirement where I have to prevent user from typing in shift+greater than in textbox.
I looked up in the ascii key code chart.I could see no ascii key for shift+greater than combination which renders ">" on the UI.
This is the code that i have tried so far.
$scope.isValidControlInputInteger = function (event) {
var keyCode = event.keyCode;
if (keyCode >= 48 && keyCode <= 57 && event.shiftKey) { // decimal numbers
return true;
} else if (keyCode >= 96 && keyCode <= 105) { // numerical pad
return true;
} else if (keyCode == 46 || keyCode == 8) { // delete and backspace
return true;
} else if (keyCode == 37 || keyCode == 39) { // arrow keys
return true;
}
else if (keyCode == 9) { // tab key
return true;
}
else {
return false;
}
};
A simple workaround that works better than checking for keyup is to just remove all instances of > upon changing the contents of the input field.
$("#field").on("keyup", function(e) {
$(this).val($(this).val().replace(/\>/g, ""))
});
Here's a fiddle.

How to use spacebar and if statements in JS?

I am making a game based off of a tutorial at http://www.lostdecadegames.com/how-to-make-a-simple-html5-canvas-game/ it is going well but I wanted to make the function that reads if the two items are touching only happen when the space bar is pressed.
if (hero.x <= (monster.x + 32)
&& monster.x <= (hero.x + 32)
&& hero.y <= (monster.y + 32)
&& monster.y <= (hero.y + 32)) {
++monstersCaught;
reset();
}
if (hero.x <= (tack.x + 32)
&& tack.x <= (hero.x + 32)
&& hero.y <= (tack.y + 32)
&& tack.y <= (hero.y + 32)) {
monstersCaught -= monstersCaught;
reset();
}
if (monstersCaught > 10) {
monstersCaught -= 10;
}
How should I fix the
if (hero.x <= (tack.x + 32)
&& tack.x <= (hero.x + 32)
&& hero.y <= (tack.y + 32)
&& tack.y <= (hero.y + 32)) {
monstersCaught -= monstersCaught;
reset();
}
so that it only goes if the space bar is pressed?
Most easy way is to know at any moment the status of your keyboard : for that you have to listen to keyboard events and update an array containing the status of each key.
This will lead to something like :
window.keyStates = []; // now you can use keyStates anywhere.
// good enough since you seem to be in the first steps.
window.addEventListener('keydown',
function(e) { keyStates[e.keyCode || e.key] = true;} );
window.addEventListener('keyup',
function(e) { keyStates[e.keyCode || e.key] = false;} );
Once you have done that, you can test anywhere, anytime, the status of the space key with :
if (keyStates[32] == true) { ... }
you might prefer, for readability, define a key object that will hold the few keycodes you use :
window.key = {
space : 32,
enter : 13,
left : 37,
up : 38,
right : 39,
down : 40
}
that way, you can write :
if ( keyStates[key.space] == true ) {
...
}
which is more easy to grasp.
(Rq : if you search for keycodes, looking here is one way : https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent )
If you use jQuery you can do something similar to this:
$(window).keypress(function(e) {
if (e.which === 32) {
//do your logic here
}
});
32 is the keycode for spacebar
Or in just javascript (Run this code in Document ready as displayunicode(event)):
function displayunicode(e){
var unicode=e.keyCode? e.keyCode : e.charCode;
if(unicode == 32){
//do your code
}
}

How to allow only numbers in a texbox but also allow entry with French keyboard

I have the following code to allow only numbers to be entered (other logic is removed for brevity).
$("input").keydown(function (event) {
var key = event.keyCode;
if ((key < 48 || key > 57) && (key < 96 || key > 105) || event.shiftKey) {
event.preventDefault();
}
});
This code works fine in English keyboards but on French keyboards the shift key is used so the logic fails there. If i remove the shift the logic fails in english keyboards.
Is there a way to detect a number is being pressed in the keydown event that will work on any type of keyboard?
Thanks
Use a custom function to check if the value of the keydown is numeric. From this previous answer (Validate decimal numbers in JavaScript - IsNumeric()):
function isNumber(n)
{
return !isNaN(parseFloat(n)) && isFinite(n);
}
And your handler UPDATED:
$("input").keydown(function (event) {
var code = event.keyCode;
//Allows left and right arrows, backspace, and delete
if(code == 37 || code == 39 || code == 8 || code == 46)
return;
var character = String.fromCharCode(code);
if(event.shiftKey || !isNumber(character)){
event.preventDefault();
}
});
I have found that event.key works better than event.keyCode. The event handler needs to be onkeydown for it to work properly. The check for whether it's a number needs to come first. Here's my code. Tested to work on IE11, Edge, Chrome, and Firefox.
$("input").keydown(function (event) {
var code = event.keyCode;
var key = event.key;
if (!isNaN(Number(key)))
return;
// allow backspace, delete, left & right arrows, home, end keys
if (code == 8 || code == 46 || code == 37 || code == 39 || code == 36 || code == 35) {
return;
} else {
evt.preventDefault();
}
});
#HostListener('keydown', ['$event']) onKeyDown(event) {
if ((e.keyCode < 48 || e.keyCode > 57) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
} else if (!this.isNumber(e.key)) {//For french keyboard
e.preventDefault();
}
}
}
isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
I had a similar problem because of 2 different keyboards. And I solve that by checking if is not a number in the key value instead of the keyCode value.
Would this work?
$("input").bind("propertychange input textInput", function() {
this.value = this.value.replace(/[^\d.]/g, "");
});
Of course, this trims the value after the input event, so I'm not sure if that's what you want

jquery only allow input float number

i'm making some input mask that allows only float number. But current problem is I can't check if multiple dots entered. Can you check those dots and prevent it for me?
Live Code: http://jsfiddle.net/thisizmonster/VRa6n/
$('.number').keypress(function(event) {
if (event.which != 46 && (event.which < 47 || event.which > 59))
{
event.preventDefault();
if ((event.which == 46) && ($(this).indexOf('.') != -1)) {
event.preventDefault();
}
}
});
You can check for the period in the same statement.
Also, you need to use the val method to get the value of the element.
Also, you want to check for the interval 48 to 57, not 47 to 59, otherwise you will also allow /, : and ;.
jQuery(document).ready(function() {
$('.float-number').keypress(function(event) {
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
Enter Number:
<input type="text" name="number" value="" class="float-number">
</body>
</html>
I think you guys have missed the left right arrows, delete and backspace keys.
$('.number').keypress(function(event) {
if(event.which == 8 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 46)
return true;
else if((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57))
event.preventDefault();
});
I think everybody forgot the case of pasting text with the mouse, in which you can't detect the keystrokes, because there's none. Here's another approach I have been working on.
// only integer or float numbers (with precision limit)
// example element: <input type="text" value="" class="number" name="number" id="number" placeholder="enter number" />
$('.number').on('keydown keypress keyup paste input', function () {
// allows 123. or .123 which are fine for entering on a MySQL decimal() or float() field
// if more than one dot is detected then erase (or slice) the string till we detect just one dot
// this is likely the case of a paste with the right click mouse button and then a paste (probably others too), the other situations are handled with keydown, keypress, keyup, etc
while ( ($(this).val().split(".").length - 1) > 1 ) {
$(this).val($(this).val().slice(0, -1));
if ( ($(this).val().split(".").length - 1) > 1 ) {
continue;
} else {
return false;
}
}
// replace any character that's not a digit or a dot
$(this).val($(this).val().replace(/[^0-9.]/g, ''));
// now cut the string with the allowed number for the integer and float parts
// integer part controlled with the int_num_allow variable
// float (or decimal) part controlled with the float_num_allow variable
var int_num_allow = 3;
var float_num_allow = 1;
var iof = $(this).val().indexOf(".");
if ( iof != -1 ) {
// this case is a mouse paste (probably also other events) with more numbers before the dot than is allowed
// the number can't be "sanitized" because we can't "cut" the integer part, so we just empty the element and optionally change the placeholder attribute to something meaningful
if ( $(this).val().substring(0, iof).length > int_num_allow ) {
$(this).val('');
// you can remove the placeholder modification if you like
$(this).attr('placeholder', 'invalid number');
}
// cut the decimal part
$(this).val($(this).val().substring(0, iof + float_num_allow + 1));
} else {
$(this).val($(this).val().substring(0, int_num_allow));
}
return true;
});
Good for integer and float values. Plus, copy/paste clipboard event.
var el = $('input[name="numeric"]');
el.prop("autocomplete",false); // remove autocomplete (optional)
el.on('keydown',function(e){
var allowedKeyCodesArr = [9,96,97,98,99,100,101,102,103,104,105,48,49,50,51,52,53,54,55,56,57,8,37,39,109,189,46,110,190]; // allowed keys
if($.inArray(e.keyCode,allowedKeyCodesArr) === -1 && (e.keyCode != 17 && e.keyCode != 86)){ // if event key is not in array and its not Ctrl+V (paste) return false;
e.preventDefault();
} else if($.trim($(this).val()).indexOf('.') > -1 && $.inArray(e.keyCode,[110,190]) != -1){ // if float decimal exists and key is not backspace return fasle;
e.preventDefault();
} else {
return true;
};
}).on('paste',function(e){ // on paste
var pastedTxt = e.originalEvent.clipboardData.getData('Text').replace(/[^0-9.]/g, ''); // get event text and filter out letter characters
if($.isNumeric(pastedTxt)){ // if filtered value is numeric
e.originalEvent.target.value = pastedTxt;
e.preventDefault();
} else { // else
e.originalEvent.target.value = ""; // replace input with blank (optional)
e.preventDefault(); // retur false
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" name="numeric" value="" placeholder="insert value">
[2017-10-31] Vanilla.js
let el = document.querySelector('input[name="numeric"]');
el.addEventListener('keypress',(event) => {
let k = event.key,
t = isNaN(k),
sc = ['Backspace'].indexOf(k) === -1,
d = k === '.',dV = el.value.indexOf('.') > -1,
m = k === '-',mV = el.value.length > 0;
if((t && sc) && ((d && dV) || (m && dV) || (m && mV) || ((t && !d) && (t && !m)))){event.preventDefault();}
},false);
el.addEventListener('paste',(event) => {
if(event.clipboardData.types.indexOf('text/html') > -1){
if(isNaN(event.clipboardData.getData('text'))){event.preventDefault();}
}
},false);
<input type="text" name="numeric">
Your code seems quite fine but overcomplicated.
First, it is $(this).val().indexOf, because you want to do something with the value.
Second, the event.which == 46 check is inside an if clause that's only passed when event.which != 46, which can never be true.
I ended up with this which works: http://jsfiddle.net/VRa6n/3/.
$('.number').keypress(function(event) {
if(event.which < 46
|| event.which > 59) {
event.preventDefault();
} // prevent if not number/dot
if(event.which == 46
&& $(this).val().indexOf('.') != -1) {
event.preventDefault();
} // prevent if already dot
});
I found this way to do this,
$.validator.addMethod("currency", function (value, element) {
return this.optional(element) || /^\$(\d{1,3}(\,\d{3})*|(\d+))(\.\d{2})?$/.test(value);
}, "Please specify a valid amount");
https://gist.github.com/jonkemp/9094324
HTML
<input type="text" onkeypress="return isFloatNumber(this,event)" />
Javascript
function isFloatNumber(item,evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode==46)
{
var regex = new RegExp(/\./g)
var count = $(item).val().match(regex).length;
if (count > 1)
{
return false;
}
}
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
jsfiddle.net
Using JQuery.
$(document).ready(function()
{
//Only number and one dot
function onlyDecimal(element, decimals)
{
$(element).keypress(function(event)
{
num = $(this).val() ;
num = isNaN(num) || num === '' || num === null ? 0.00 : num ;
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57))
{
event.preventDefault();
}
if($(this).val() == parseFloat(num).toFixed(decimals))
{
event.preventDefault();
}
});
}
onlyDecimal("#TextBox1", 3) ;
});
One-more plugin, based on Carlos Castillo answer
https://github.com/nikita-vanyasin/jquery.numberfield.js
Adds method to jQuery object:
$('input.my_number_field').numberField(options);
where options is (you can pass any or no options):
{
ints: 2, // digits count to the left from separator
floats: 6, // digits count to the right from separator
separator: "."
}
Using jQuery and allowing negative floats :
// Force floats in '.js_floats_only' inputs
$(document).ready(function() {
$('.js_floats_only').each(function() {
// Store starting value in data-value attribute.
$(this).data('value', this.value);
});
});
$(document).on('keyup', '.js_floats_only', function() {
var val = this.value;
if ( val == '-' ) {
// Allow starting with '-' symbol.
return;
} else {
if ( isNaN(val) ) {
// If value is not a number put back previous valid value.
this.value = $(this).data('value');
} else {
// Value is valid, store it inside data-value attribute.
$(this).data('value', val);
}
}
});
For simple cases and without hardcoding some html instructions would fit that pretty enough
<input type="number" step="0.01"/>
$('.number').keypress(function(event){
if($.browser.mozilla == true){
if (event.which == 8 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 9 || event.keyCode == 16 || event.keyCode == 46){
return true;
}
}
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
This works in all browsers.
<input type="text" data-textboxtype="numeric" />
<script>
$(document).on('keydown', '[data-textboxtype="numeric"]', function (e) {
// Allow: backspace, delete, tab, escape, enter and . and -
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190, 109, 189]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right, down, up
(e.keyCode >= 35 && e.keyCode <= 40)) {
// let it happen, don't do anything
return true;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
return false;
}
return true;
});
</script>
Below Code I am allowing only Digits and Dot symbol.
ASCII characters number starts in 47 and ends with 58 and dot value is 190.
$("#Experince").keyup(function (event) {
debugger
if ((event.which > 47
&& event.which < 58) ||event.which== 190) {
if ($("#Experince").val().length > 3) {
}
} // prevent if not number/dot
else {
$("#Experince").val($("#Experince").val().slice(0, -1))
}
});

Categories