checking two values on 'enter' press - javascript

I want to check the value of a input field against a value in my js object on pressing enter. the if (document.getElementById("barcode").value === element.anr) works. however, i only want it to execute document.getElementById("next").click(); if barcodecounter is equal to element.menge.
Basically if element.menge has a value of 5, the first time document.getElementById("barcode").value is equal to element.anr I want barcodecounter to increase by 1 and when its equal to element.menge it should execute document.getElementById("next").click();.
Currently if e.g. element.menge is 5, it still executes document.getElementById("next").click(); even when I only provided it once instead of 5 times.
What am I doing wrong?
document.getElementById("barcode").addEventListener("keypress", function(e) {
let barcodecounter;
if (event.which == 13 || event.keyCode == 13) {
if (document.getElementById("barcode").value === element.anr) {
barcodecounter++;
if (barcodecounter = element.menge) {
document.getElementById("next").click();
}
console.log(document.getElementById("barcode").value, element.anr);
console.log(element.menge);
}
else if (document.getElementById("barcode").value != element.anr){
alert("Falscher Artikel");
}
}
});

You are using an assignment = not a boolean compare ==, simple change. I also added some adjustments to the code to initialize stuff. element might be something else but was not in there
// used this but not declared:
//let element = {};
//element.anr = 0;
//element.menge = 0;
//OR use, I assume numerics heres
let element = {
anr: 0,
menge: 0
};
document.getElementById("barcode").addEventListener("keypress", function(e) {
let barcodecounter = 0;// set initial value;
if (event.which == 13 || event.keyCode == 13) {
if (document.getElementById("barcode").value === element.anr) {
barcodecounter++;
if (barcodecounter == element.menge) {
document.getElementById("next").click();
}
console.log(document.getElementById("barcode").value, element.anr);
console.log(element.menge);
} else /* no need for else if here */ {
alert("Falscher Artikel");
}
}
});

Related

Move player javascript

I do not understand this part :
self.keyDown = function() { keys[event.keyCode] = 1; };
self.keyUp = function() { delete (keys[event.keyCode]); };
explain what this code does, please)
MVC :
Controller:
this.init = function() {
keys = {};
}
self.trgt = function(){
if(this.event.target === myContainer.querySelector('#start')) {
myModel.startGame();
window.addEventListener('keydown', self.keyDown);
window.addEventListener('keyup', self.keyUp);
}
}
self.keyDown = function() {
keys[event.keyCode] = 1;
};
self.keyUp = function() {
delete (keys[event.keyCode]);
};
self.moveHero = function(keycode) {
myModel.moveHero(keycode);
};
setInterval(function() {
for (let keycode in keys) {
self.move(keycode);
}
}, 20);
Model:
if (!sometask) {
if (keycode == 37 || keycode == 65) {
self.moveLeft();
}
if (keycode == 38 || keycode == 87) {
self.moveTop();
}
if (keycode == 39 || keycode == 68) {
self.moveRight();
}
if (keycode == 40 || keycode == 83) {
self.moveBottom();
}
}
};
the code in question:
self.keyDown = function() { keys[event.keyCode] = 1; };
self.keyUp = function() { delete (keys[event.keyCode]); };
is just assigning which keys are currently pressed. Lets say event.keyCode = 37, In this instance your keys variable, which is an object, will now have a property that says keys[37] = 1, and it will remain that way until the keyUp function is called, deleting it. Whiile keys[37] = 1, the character will continue moving left, and this will stop once that key is deleted.
self.keyDown = function() { keys[event.keyCode] = 1; };
self.keyUp = function() { delete (keys[event.keyCode]); };
Translating to plain English:
If the user press the keyDown (number 40) then set the key 40 in the object keys to 1.
If the user press the keyUp (number 38) then delete from the keys object the key 38
These lines are to set functions that will be called each time the event keyDown (press a key) or keyUp (release the key) are called.
So let's focus on the actual code inside the function :
for keyDown, it sets a variable in a dictionary to a value. for instance, if you press down 'a', 'a' key on the keyboard has some int value which is 65 (see https://keycode.info/), and it will set the keys[65] = 1.
As long as you keep the button press, this value will stay, but as soon as you release it, the value is unset by using delete .
And so on for each keyboard key.
Then the main loop of the game will look which variables are set (by using "for ... in keys), and will execute a move function for each variable that has a special values, corresponding, I guess, to a-w-s-d or left-up-right-down.

loop won't go through first if statement

My code will only go through to the first if statement where it checks the value of key for headline1 etc... The first if statement works properly but it won't work with any of the following if statements when the first one isn't true. I've switched the second statement to the first where it checks for 'desc1' and then it works for that one only.
The purpose of this function is to check each key of an object and return the key when its value is over a certain length so I can add a class and show user some warning. This is in Vue JS so ads is in data and characterCheck is in computed property.
ads: [
{
headline1: '_keyword_',
headline2: 'Online',
headline3: 'Free',
desc1: 'Buy online _keyword_',
desc2: ' Vast collection of _keyword_',
finalurl: 'www.books.com',
path1: '',
path2: '',
boolean: true
}
]
characterCheck () {
for(var x = 0; x < this.ads.length; x++){
if(this.ads[x]['boolean'] == true) {
for(var key in this.ads[x]){
var length = this.ads[x][key].replace(/_keyword_/g, this.activeKeyword).length
if( key === 'headline1' || key === 'headline2' || key === 'headline3'){
if(length > 30){
return key
}
} else if( key == 'desc1' || key == 'desc2'){
if(length > 90){
return key
}
} else if( key == 'path1' || key == 'path2'){
if(length > 15){
return key
}
} else {
return false
}
}
}
}
}
When your first nested if condition fails, the code goes to next subsequent else-if. For some particular value, all the if and else-if block fails and code lands on final else block which contains a return statement.
If your code reaches even once there, the entire function execution immediately stops and false value is returned.
Since, you wish to wait as long as you have not looped through all the values, remove the else part and add a simple return statement to the end of the for loop like this:
function characterCheck () {
for(var x = 0; x < this.ads.length; x++) {
if(this.ads[x]['boolean'] == true) {
for(var key in this.ads[x]) {
var length = this.ads[x][key].replace(/_keyword_/g, this.activeKeyword).length
if( key === 'headline1' || key === 'headline2' || key === 'headline3') {
if(length > 30) {
return key
}
}
else if( key == 'desc1' || key == 'desc2') {
if(length > 90) {
return key
}
} else if( key == 'path1' || key == 'path2') {
if(length > 15) {
return key
}
}
}
}
}
return false
}

Number validation along with decimals in key press event

I am doing validation of number except on case. I am doing validation in key press event.
This is the process how am doing my validation..
Output length = Integral + decimals
Example: Integral = 5, decimals = 3
If user enter five digits then am not allowing to enter 6th digit. (i.e. 12345).
But if he type '.' then after am allowing to 3 decimals (i.e. 12345.678). This is working perfectly.
Am facing the issue with below case.
If user enter 1.234 then he navigating to before '.' place using arrows or by mouse click, then user unable to enter another digit. Because I am checking either the integral part or decimal part match the length then I am returning false.
Can any one help me out this. I can do with key up event, but I am trying to achieve this by key press event only. Is there any way to get the position where user entering the digit, if yes then I can get one solution.
var integral = 5, decimals = 3;
//below code in the key press event
if ([8, 9, 13, 37, 39,46].indexOf(e.keyCode) != -1) {
return true;
} else if (e.keyCode == 190 && !e.shiftKey && decimals) {
_value = $(this).val();
if (_value.indexOf('.') != -1) {
return false;
}
return true;
} else if (48 >= e.keyCode || e.keyCode <= 57) {
_value = $(this).val();
if (decimals) {
_value = _value.split('.');
if (_value[0].length == integral || (_value[1] || '').length == decimals) {
return false;
}
return true;
} else {
if (_value.length == integral) {
return false;
}
return true;
}
}
return false;
I used selectionEnd for getting position of where user is typing the digit. Using that I did it.
var evt = e.target || e.srcElement;
_value = $(evt).val();
if ([8, 9, 13, 37, 39, 46].indexOf(e.keyCode) != -1) {
return true;
}
else if (e.keyCode == 190 && !e.shiftKey && decimals) {
if (_value.indexOf('.') != -1) {
return false;
}
return true;
}
else if (48 >= e.keyCode || e.keyCode <= 57) {
if (decimals) {
var isHavingDot = false;
var dotPosition = '';
if (_value.indexOf('.') != -1) {
isHavingDot = true;
dotPosition = _value.indexOf('.')
}
var length = _value.length;
if (isHavingDot) {
_value = _value.split('.');
if (evt.selectionEnd <= dotPosition) {
if (_value[0].length >= integral) {
return false;
}
}
else if ((_value[1] || '').length >= decimals) {
return false;
}
}
else {
if (_value.length >= integral) {
return false;
}
}
return true;
}
else {
if (_value.length == integral) {
return false;
}
return true;
}
}
return false;
If you already know how to do it with the keyup event, then you should be able to take that code and insert it into the keypress handler and implement it on the value that would be in the input if you pass the value through.
For example (I assume your validation works like in the example):
$("#myinput").keypress(function (e) {
//first figure out what the value would be if the keypress were passed through
var key=(e.which) ? e.which : e.keyCode;
var inputvalue=String.fromCharCode((96 <= key && key <= 105)? key-48 : key)
var caretPos = document.getElementById("myinput").selectionStart;
var currentvalue=$("#myinput").val();
var outputstring=currentvalue.substring(0, caretPos) + inputvalue + currentvalue.substring(caretPos);
//allow decimals through
if (outputstring===".") {
e.preventDefault();
$("#myinput").val("0.");
return false;
}
//cancel keypress if they string already has a decimal
if(key===46) return (outputstring.split(".").length - 1)>2;
//now perform the truncation and validation
e.preventDefault();
var outputvalue=parseFloat(outputstring);
var decpart=Math.trunc((outputvalue- parseInt(outputvalue)) * 1000)/1000;
var intpart=Math.floor(outputvalue);
//perform your test on the output value here - only need to test the integer part, since the decimal part is truncated
var outputtest=String(intpart).length<=5;
if (outputtest){
//insert the value if it looks okay
$("#myinput").val(intpart+decpart);
}
return false;
});

Trouble with basic javascript

I'm trying to do some extremely simple form validation, my current problem is that my window.onload function doesn't call in the function I specify.
When I watch the flow of logic with firebug it just skips to the end of the code.
Here is an example of my code:
window.onload = init;
function init() {
var regForm = document.getElementById("registerform");
regForm.onsubmit = validatepostcode();
}
function validatepostcode() {
var postCode = document.getElementById("postcode");
var postCodeStr = postCode.charAt(0);
var state = document.getElementById("state");
var result = true;
if (postCodeStr == 3 || 8 && state == "Vic") {
result = true;
} else if (postCodeStr == (1 || 2) && state == "NSW") {
result = true;
} else if (postCodeStr == (4 || 9) && state == "QLD") {
result = true;
} else if (postCodeStr == 0 && state == "NT" || state == "ACT") {
result = true;
} else if (postCodeStr == 6 && state == "WA") {
result = true;
} else if (postCodeStr == 5 && state == "SA") {
result = true;
} else if (postCodeStr == 7 && state == "TAS") {
result = true;
} else
result = false;
if (result = false) {
alert("Your postcode does not match your state")
}
}
Five problems:
In init, you have this:
regForm.onsubmit = validatepostcode();
That calls validatepostcode and puts its return value in onsubmit. You probably meant to put the function itself it, not its return value in. Remove the parentheses:
regForm.onsubmit = validatepostcode;
In validatepostcode, you're fetching elements like this:
var postCode = document.getElementById("postcode");
…but then try to use them as values, like this:
var postCodeStr = postCode.charAt(0);
But an element and the current value of that element are not the same thing. More likely, you meant to retrieve the value on the first line:
var postCode = document.getElementById("postcode").value;
Same goes for state.
In validatepostcode, you have lines like this:
} else if (postCodeStr == (1 || 2) && state == "NSW") {
Specifically, 1 || 2 won't work like that. It will look at them like booleans and say, “one or two? well, they're both truthy…true it is!” and you'll essentially be doing
} else if (postCodeStr == true && state == "NSW") {
(Actually, it uses 1, not true, since the first operand was truthy, but that's not the important point here.)
Instead of using that abbreviated notation, you'll have to write it out longhand:
} else if ((postCodeStr == 1 || postCodeStr == 2) && state == "NSW") {
You mixed up = and == here:
if(result=false){
= will set result to false and leave the condition always false. Change it to == to test equality:
if(result==false){
You probably meant to return result at the end to prevent the form from being submitted when there is a validation error. With the other changes applied, you'd get an alert if there was a validation error, but it'd go on submitting anyway. As such, add a return result at the end of the validatepostcode function.

How to limit Tab listener to callback only if the textbox has change

I'm trying to implement a Tab key listener for a textbox.
$('#mytextbox').live('keydown', function (e) {
if (e.keyCode == 9 || e.which == 9) {
// TO DO SOMETHING
}
});
However, for some reason I need to limit the tab listener's callback to invoke only when the textbox has changed. Is there anyway to do this?
You might be able to check the value of the input field to make sure it's different from it's original value?
E.g.
$('#mytextbox').live('keydown', function (e) {
if ((e.keyCode == 9 || e.which == 9) && ($('#TextBox').val() != 'Starting Value')) {
// TO DO SOMETHING
}
});
You can do it just like:
var data = "";
$('#mytextbox').live('keydown', function (e){
if(e.which == 9 || e.keyCode == 9){
if($(this).val() != data){
alert('changed!');
data = $(this).val();
}
}
});
http://jsfiddle.net/DDCZS/1/
Or without storing / knowing value of that textbox:
var changed = false;
$('#mytextbox').on('keydown', function (e) {
if (e.which == 9 && changed) {
e.preventDefault();
// TO DO SOMETHING
alert("works");
changed = false;
} else {
changed = true;
}
});
http://jsfiddle.net/9a37b/

Categories