This is probably a really simple thing but I can't for the life of me figure out or find anything remotely like the issue. I'm fairly new to Javascript and I'm doing some simple form validation on HTML fields. The two problems at hand are these:
if(minSquare.search(intCheck) == -1 || minSquare < 500 || minSquare > 5000 || minSquare > maxSquare)
{
errorPrint.innerHTML += "Incorrect minimum square feet amount <br />";
errors++;
}
if(maxSquare.search(intCheck) == -1 || maxSquare > 5000 || maxSquare < 500)
{
errorPrint.innerHTML += "Incorrect maximum square feet amount <br />";
errors++;
}
minSquare/maxSquare are the values taken from the HTML fields. As you can see the square feet values (in a real estate setting) are supposed to be between 500-5000 and have to be an integer. The logic is there, but every time I submit the form, the error for incorrect minimum square feet prints if the value is below 1,000 despite the lower limit being 500. This is the same case for another pair of fields in that if the value is below 100,000, it won't print despite its own lower limit being 30,000.
For some reason when I enter 500 for the minimum amount and 5000 for the maximum amount (the proper range), it will submit no problem. But if I enter say, 501 and 5000 it will throw an error for the minimum value. I have no idea why this is happening. I don't think it's a browser issue; tried on both Chrome and Firefox, same problem. Any help appreciated; the more stupid the problem the quicker I can close this up =)
EDIT: Fixed the problem. Knew it was simple. As per advice below, I just needed to parse the inputs and then I needed to get rid of the RegExp search method that would only work if the variable being searched is a string. Thanks to those who replied.
Related
this is my second post today as the original wasn’t clear and I was urged to repost because despite getting some good answers they did not fit the requirements of the code. I have been challenged to write a program in JavaScript that allows the user to perform several tasks, one of which is to ask the user for a number and calculate the factorial of that number and then display it in the format listed in the requirements. As I do not know much about Java script I used already asked questions and managed to get the calculation to work but could not figure out how to get the required output whilst still meeting the requirements.
Requirements:
• Can only use the provided variables Number (variable initialised as 0 to hold user input) Factorial (variable initialised to 1 to hold value of calculated factorial) Count (variable to hold number of times loop is executed for performing factorial calculation). This is a limitation set by the challenge and not me
• Cannot use fancy libraries
• Need to use a loop solution for the output. The answers on the other post required introducing new variables, perhaps it is my lack of understanding but perhaps the poorly written pseudo code I have obtained since the last post may help.
• Be output in the format: (it is an alert so that part of the program is fine)
The factorial of 5 is 5*4*3*2*1=120
OR
5! is 5*4*3*2*1=120
Poorly written pseudo code:
Code:
//prompts the user for a positive number
var number = parseInt(prompt("Please enter a positive number"));
console.log(number);
//checks the number to see if it is a string
if (isNaN(number))
{
alert("Invalid. Please Enter valid NUMBER")
}
//checks the number to see if it is negaive
else if (number < 0)
{
alert("Please Enter valid positive number");
}
//if a positive integer is entered a loop is started to calculate the factorial of the number the user entered
else {
let factorial = 1;
for (count = 1; count <= number; count++) {
factorial *= count;
}
//Sends the inital number back to the user and tells them the factorial of that number
alert("The factorial of " + number + " is " + factorial + ".");
}
I know there are many similar questions, including my first post which this one now succeeds as I looked around and used them to help me get this far but it is getting the output into the required format that I'm struggling with. I am told it is possible with a loop but do not know where to begin implementing that and I'm only allowed to use that solution.
Again, I would like to apologise for my first post, the given answers would work great if not for the incredibly ridiculous restrictions set by the challenge provider, who is also responsible for giving me rubbish pseudo code, which isn't what I'm going for but I am using to consider the loop.
I appreciate the time it takes to read this amd provide solutions so I will go back and try and mark all working answers in the last post for any normal problems people might search for answers for.
This is a bit of a dirty hack but it should satisfy the condition that no other variables than number, count, and factorial are used.
let number = 5;
let factorial = 120;
// ^ Do your own calculation for this
alert(`The factorial of ${number} is ${Array.from(Array(number + 1).keys()).slice(1).reverse().join("*")}=${factorial}`)
So what is going on here?
We use an interpolated template string to produce the desired output, expressions inside ${these things} are evaluated as strings. And what is the mess we put in there?
Array.from(Array(number + 1).keys())
The expression above creates the array [0,1,2,3,4,5].
.slice(1) gives us [1,2,3,4,5]
.reverse() gives us [5,4,3,2,1]
join("*") gives us "5*4*3*2*1"
Which when all put together gives us The factorial of 5 is 5*4*3*2*1=120
And voila! The output is printed in the desired format without introducing any new variables.
Edit: Oh and you do not need to use an interpolated string for this. You may as well concatenate regular strings together as you have done in your question. e.g.
"The factorial of " + factorial + " is " + Array.from(Array(number + 1).keys()).slice(1).reverse().join("*") + "=" + factorial
I've always had a hard time understanding properly number format tokens and this occasion seems no exception.
A small condition that I place at the bottom of my scripts lets me differentiate how varying ranges of numbers appear on the sheet:
if (value < 1) {var a = a.toFixed(8);}
if (value > 1 && value < 10) {var a = a.toFixed(4);}
if (value >=10) {var a = a.toFixed(2);}
I would like to transpose this pattern to the setNumberFormat() method however for the sake of simplification and hopefully speeding up the scripts.
Now, this guide suggests that specific conditions can be set in order to provide a broader range of possibilities; that's my case I thought, the problem is that I simply can't make the script work:
this one works
var range = sheet_Numbers.getRange(['C:E']);
range.setNumberFormat("[<1]###0.########;[>10]####.##;##.####");
but doesn't produce the expected result: I meant numbers between 1 and 10 displaying 4 digits after the decimal point, not 3 .
All my other attempts at applying the guides directions return error instead.
Following the guide I thought I could provide something like this, but that doesn't seem to be the case however:
var range = sheet_Numbers.getRange(['C:E']);
range.setNumberFormat("[[<1]####.########;[>10]####.##;####.####];[NEGATIVE FORMAT];[ZERO FORMAT]");
Any suggestion?
If you want 5.655 to be rendered as 5.6550(4 digits after the decimal regardless of significance), use 0 instead of #
"[<1]###0.########;[>10]####.##;##.0000"
or more generally
"[<1]###0.00000000;[>10]####.00;##.0000"
Am totaling several form fields where users put in hours of the day. However, some users would like to put an "X" if they were not present that day. So I tried several different if statements to try to get the calculation to recognize "X" as a zero when running the calculation but still show an X in the form field. I went as far as creating a hidden form field and default its value to zero and that is the last thing I tried.
Here is my formula (please keep in mind, I will have to use this for each day of the week but I just was playing around with the first one)
var v1 += getField("mon1_str."+row).value;
if(v1 == "X") event.value = "defaultvalue";
else event.value = "";
The first line of script gets my value no problem. Its the second line and third line where i am not having any luck. It should be noted that no errors are coming up in the console window. "defaultvalue" is the name of my hidden form field to grab a value from.
The + tries to convert the string to a number. But 'x' can't be converted to a number, so it results in NaN.
console.log(+'X');
Try saving the plain value, checking if it's 'X', and then converting it to a number later.
I'm making a form which older people have to use to register for a health service. (School project)
I want to make it so that if the enter less than or more than the allow number of characters for the alert box to state how many characters they have entered in their last password to show where they went wrong. I have written or rather copied and edited the code to validate.
if (pw.length < o.length[8] || pw.length > o.length[25])
alert("Your password must be between 8 to 25 chacters. The one you entered had * characters")
//Would have to remember how many were entered, and then produce it
return false;
I have done a bit of researching nothing I could find.
However if you even had some pointers on how I would go about I would be grateful.
if (pw.length < 8 || pw.length >25){
alert("Your password must be between 8 to 25 chacters. The one you entered had "+pw.length+" characters");
return false;
}
You're looking for..
if(pw.length < 8 || pw.length > 25)
alert("Bad Password!");
pw.length returns a number representing the length of the password. It is not an array so you cannot try and access indexes like you're doing with o.length[8]. Assuming ois another String.
What is o in this context?
why not
if (pw.length < 8 || pw.length > 25) ...
no need for o.length...
This is the problem with copy and paste, which you mentioned you did. You got code, but don't understand it. You would be better served writing your own code....
Assuming pw is your password input box (gotten using getElementById) you basically need to check the length of the value in the box with pw.value.length, which will return an integer. That should put you on the right track
I have the following code
if (msg.position == 0)
//removed for brevity
else if (msg.position == txtArea.value.length)
//removed for brevity
else {
//ERROR: should not reach here.
errorDivTag.innerHTML += msg.position + " " + txtArea.value.length;
}
I'm having some really weird situations where I'm getting the error in the last code block, but the printed positions show that msg.position is in fact equal to the txtArea.value.length. This only happens 1% of the time, almost as if I have some kind of race-condition in my code where the two are NOT equal during the second if statement, but equal when I print in the error message.
Any ideas?
If you use
parseInt(msg.position)
without a radix, you will run into problems with 08 and 09, because they are parsed as octal numbers and giving NaN. Always use a radix:
parseInt(msg.position, 10)
To start with, always use ===. That will prevent JavaScript from automatically coercing the types in the comparison, which means you'll be able to spot all sorts of bugs much more easily. In this case, it's possible you have some whitespace (which is basically impossible to see in the output) that is causing a string comparison instead of the (I assume) desired numeric comparison.
Also, I'm assuming you really meant to have { after your if and else if conditions. If not, that could be causing all sorts of strange behavior, depending on the code you removed due to brevity concerns. If you didn't, then you've got an extraneous } before your else condition.
UPDATE: Set a breakpoint in Firebug/DeveloperTools/DragonFly/whatever and inspect the values as the comparison occurs.
Did you try changing the statement to...
parseInt(msg.position, 10) == txtArea.value.length
=== is more strict than == and is often useful. But this is the opposite problem as what you have here, where something looks equal, but isn't == or === (if something isn't ==, it will never be ===).
Is msg.position a String? Perhaps it contains a space or another similar character.
I had this problem today with a checksum value in one of my js modules. A test was showing that two values were not equal, yet printing the values showed they were equal.
Ran it in the debugger and (re-)discovered that integer types in Javascript are 64-bit floating quantities. One of the numbers was displaying as negative in the debugger - exactly (0xFFFFFFFF+1) less than the other number. Somehow when printed, they displayed as exactly the same.
I was using a custom routine to format them in hex, which probably had something to do with it. That combination of circumstances seems unlikely in your case though.
I discovered the sign issue in my code by computing the delta between the numbers, and displaying that. It showed up as MAX_UINT32 + 1, which reminded me that these numbers are really 64-bit floats.