My code couldn't be simpler...
if (iWant > thereAre){
msg = "There's only "+thereAre+" left, but you want "+iWant
} else {
gimmie
}
But sometimes it works.. sometimes it does the else{ every time... sometimes the if{ every time... I will switch the > to a < and then it will still function as before....?
Can JS be broken?
I'm ending up with messages that say "There's only 87 left, but you want 2"... sometimes...sometimes it works great.
The iWant var is getting pulled from a form post
The thereAre var is getting pulled from a MySql COUNT
Please help.. I feel like I'm going crazy.
Sometimes a variable may be a number 4 or the string '4'.
If you want number comparison, not string comparison, then you can multiply by 1 or use parseInt/parseFloat to guarantee that you are dealing with numbers.
if (1*iWant > 1*thereAre ){
too much;
} else {
ok;
}
However, if user input somehow becomes involved and iWant is "two" or "2oops" instead of 2 or "2", this code will still function but not in a useful way.
Optionally you might want to detect non-numbers if it is an issue.
Related
Hope someone can help with this. I have come across an issue with the application im testing. The developers are using vue.js library and there are a couple of fields which reformat the entered test. So for example if you enter phone number, the field will automatically enter the spaces and hyphens where its needed. This is also the same with the date of birth field where it automatically enters the slashes if the user does not.
So the issue I have is that using both 'setValue()' or 'sendKeys()' are entering the text too fast and the cursor in the field sometimes cannot keep up and the text entered sometimes appears in the incorrect order. For example, if I try to enter '123456789'. Some times it ends up as '132456798' (or any other combination). This cannot be produced manually and sometimes the test does pass. But its flakey.
What I wanted to do was to write a custom command to do something where it enters the string but in a slower manner. For this I need to have control of how fast I want the text to be entered. So I was thinking of something like this where I can pass in a selector and the text and then it will enter one character at a time with a 200 millisecond pause in between each character. Something like this:
let i = 0;
const speed = 200; // type speed in milliseconds
exports.command = function customSetValue(selector, txt) {
console.log(selector);
console.log(txt);
if (i < txt.length) {
this.execute(function () {
document.getElementsByName(selector).innerHTML += txt.charAt(i);
i++;
setTimeout(customSetValue, speed);
}, [selector, txt]);
}
return this;
};
When running document.getElementsByName(selector) in browser console I get a match on the required element. But it is not entering any text. Also note that I added a console.log in there and I was actually expecting this to log out 14 times but it only logged once. So itss as if my if condition is false
I checked my if condition and it should be true. So not sure why its not reiterating the function. Any help is much appreciated.
Also if it helps. I am using the .execute() command to inject javascript which is referenced here: https://nightwatchjs.org/api/execute.html
And the idea on this type writer is based on this: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_typewriter
We ended up taking a different approach much simpler. Wanted to post here in case anyone else ever needs something similar
exports.command = function customSetValue(selector, txt) {
txt.split('').forEach(char => {
this.setValue(selector, char);
this.pause(200); // type speed in milliseconds
});
return this;
};
I have this if statement i have came up with here:
var TotalMoney=0;
var Orbs=0;
if (TotalMoney.length==2) {
Orbs+=1;
}
What this code is supposed to do is if the the "TotalMoney" value digit length equals 2,
example (the number 10 has 2 digits)
then it will add 1 "Orb" to the "Orbs" value. Currently, it does nothing. There is HTML and CSS linked to this code but i figured the problem is in this code as it works fine for everything else. Please fix it as i have been trying for hours. Thanks!
For my second question that i just found out with this code here:
var totalMoney=0;
var orbs=0;
if (totalMoney.toString().length==2) {
orbs+=1;
}
This works on getting the number value digits as 2 digits long. The problem now is that once it reaches 10, every time that number goes up (10-99) all the way up, it will add 1 orb each time. I only want it to add 1 orb only when it gets to the 2 digit number (10) and stops adding 1 orb after it reaches it. How can i achieve this? Thanks!
TotalMoney is a number, so it doesn't have a length property. You can check the length of the number by first converting to a string: TotalMoney.toString().length.
Number object in js has no length property, so TotalMoney.length return undefined.
If you want count digits you may use this:
if (TotalMoney.toString().length == 2) {
Orbs+=1;
}
But if TotalMoney will be negative, -1 for exmple, Orbs wil be incremented.
I think there are better way to find all 2-digits number:
if (TotalMoney>9 && TotalMoney<100) {
Orbs+=1;
}
TotalMoney is numeric
so to find its length use this code
TotalMoney.toString().length;
Instead of
TotalMoney.length;
so try to modify your code as below:
var TotalMoney=0;
var Orbs=0;
if (TotalMoney.toString().length==2) {
Orbs+=1;
}
Length is property of array & string.It can not be applied on other variables.
If you want to count number of digits you can do
if(TotalMoney>9)
Or you can convert it to string then check it's length
if(TotalMoney.toSting().length>2)
here are some ideas and general comments on your code.
// recommended to start with lower case. upper case such as 'TotalMoney'
// is stylistically reserved for constructors.
var totalMoney=0;
// again - changing form Orbs to orbs;
var orbs=0;
// recommended to use '===' until you are more experienced with JavaScript and
// know about the 'gotchas' that '==' might produce.
// you will be able to check the length of totalMoney only after converting it to a string.
if (totalMoney.toString().length === 2) {
orbs+=1;
}
Finally, totalMoney of 0 will not add one to orbs. But totalMoney of 10, as you mentioned, will.
I have two variables, totalGuess and condensedAnswer. I am creating a jQuery click event and if totalGuess doesn't equal condensedAnswer then the click event will not occur and a div called message will display the message "Sorry, but your answer is incorrect. Please try again."
The problem is, totalGuess in the if statement is never equal to condensedAnswer. I've tried seeing typeof and they are both strings. I've tried console.log(totalGuess+"\n"+condensedAnswer); and they both return the same value. I've tried hardcoding the condensedAnswer, and totalGuess was able to be equal to the hardcoded answer. But when I tried comparing condensedAnswer with the hardcoded answer, it's not equal, even though the console.log value for condensedAnswer is the same. I'm not what's wrong.
Here's the code snippet:
$('.submitGuess').click(function(e){
var totalGuess = "";
var condensedAnswer = answer.replace(new RegExp(" ","g"), "");
$('.crypto-input').each(function(){
totalGuess += $(this).val();
});
// if incorrect guess
if(totalGuess !== condensedAnswer) {
$('.message').text("Sorry, but your answer is incorrect. Please try again.");
e.preventDefault();
}
// if user wins, congratulate them and submit the form
else {
return true;
}
});
If it helps, here's the page, just a random test cryptogram plugin for Wordpress:
http://playfuldevotions.com/archives/140
The problem has nothing to do with the check. The problem is the fact your value you are checking against has hidden characters. However you are getting that string has the issue.
Simple debugging shows the problem
> escape(totalGuess)
"God%27sMasterpieceMatthew15%3A99Psalms129%3A158"
> escape(condensedAnswer)
"God%27sMasterpieceMatthew15%3A99Psalms129%3A158%00"
It has a null character at the end.
Now looking at how you fill in the answer you have an array with numbers
"071,111,100,039,...49,053,056,"
Look at the end we have a trailing comma
when you do a split that means the last index of your array is going to be "" and hence why you get a null.
Remove the trailing comma and it will magically work.
Okay, I'm doing an exercise to learn Javascript, where I need to make a simple Sudoku app. There's a function to create the Sudoku field, and each little square is in a div with an id identifying the row number and column number.
Now the idea is that if a user clicks on an open field, a prompt appears asking him/her to enter a number. If the number is between 1 and 9, that number is then displayed inside the field.
I first invoked the function like this:
node.onclick=function(){fillNumber(this.id);};
This had the unexpected side-effect of making the prompt box appear three times in a row whenever a click was performed. Yet, it was clear that the first input by the user was accepted, stored and added to the div just like it was supposed to. The input from the second and third prompt box is simply lost.
I solved the problem by using the following invocation:
node.onclick=function(){if (parseInt(this.id) > 0) fillNumber(this.id);};
Yet I've no idea why this works (this is copied from a fellow student who did it this way, but doesn't know why). The value of this.id is always something like this: "11", "12", "13", "21", "22", ... So I don't even see the point of first parsing it to an int or checking whether it's bigger than 0. It always is both an int and bigger than 0 as far as I can see. Regardless, the code of the method itself didn't change and the method is invoked with the exact same argument value.
Here's the method fillNumber:
function fillNumber(id){
var input = -1;
do{
input = parseInt(prompt("Enter a number between 1 and 9: ", ""));
}while(input < 1 || input > 10);
var i = parseInt(id/10), j = id%10;
numbers[i][j] = input;
var tekst = document.createTextNode(numbers[i][j]);
document.getElementById(tekst).appendChild(tekst);
}
Can anyone explain this to me?
I may suggest you to check whether there are elements upon each other - this might be the reason for three prompts in a row.
I guess the reason the other student wrote parseInt(this.id) is the same.
He tries to parse an id into an int to escape the other clicked elements, so he makes sure the id is a valid number.
Try to use next lines:
node.onclick=function(e){
if( e.stopPropagation ) e.stopPropagation();
if( e.preventDefault ) e.preventDefault();
else e.returValue = false;
fillNumber(+this.id);
}
Note the + at +this.id parses a string to an integer or a float.
Ladies and gentlemen,
I'm stuck. I've been pondering this (and obviously have failed since I'm asking for your valuable assistance) in trying to get my code to work.
I need to come up with a simple (...I'm sorry, i'm new to this) code that prompt users to keep entering names using a loop. If the user does not enter 'q'(without quotes) and if the value entered is NOT null, then the value entered should be added to the array (in my case, names).
If the user enters 'q', the loop should stop, 'q' will not be entered in the array and the list of names should be printed (through the second function in my code).
Here's what I have so far... I can make the code work if I tell the loop to run i<5... it runs 5 times and then it stops. But it fails if i do i < names.length..it causes it say that length is null or not an object (on line 10). That's problem one. And for the life of me, I can't figure out how to add the logic that will run the loop until user enters q.
Please help!
Thank you.
function getNames(){
var names = new Array();
for(i=0;i<names.length;i++){ /*if i do i=0;i<5;i++, the code works; it doesn't with this*/
names[i] = prompt("Enter an item to add to the Name list (enter \'q\' to quit","");
}
printNames(names);
}
function printNames(names) {
for(x=0; x < names.length;x++){
document.write(names[x] + '<br />');
}
}
getNames();
printNames();
I am sure somewhere in your class/book it talks about while loops. So you want to use a while loop if you want them to keep entering without a limit.
while (myCondition===true) {
//do something
}
Now look at your for loop and figure out why it is failing.
for(i=0;i<names.length;i++)
Look at what it is doing:
i = 0
names.length = 0
Is 0 < 0?
Well to start with Problem 1:
Your names array begins with a length property of 0 and so your first for loop doesn't run because 0 is not less than 0.
Which leads to Problem 2:
Again since nothing was entered into your names array your second for loop again does nothing and doesn't execute document.write because the length property of your array is still 0.