How to compare a number in if condition? - javascript

I wrote this code for the user to guess a password exactly 4 times but I am not able to compare the input with the pin, is the way I have compared here wrong? can I not compare the number directly? like
if (input !== 0704)
is it wrong if I'm writing the number directly like this? it works fine if I replace the number with a string.
let pin = 0704;
let count = 0;
for (i=1; i<=4; i++) {
let input = prompt('please make a guess');
if (input !== 0704 ) {
console.log('Sorry that was wrong');
count++;
}
else {
console.log('That was correct!')
break;
}
}

if by input you are meaning html input then you need to compare the value with a string since output of html input is in string format. Also note the preceding 0 in 0704 will be ignored. So in this case you can use 0704 as string and perform comparison
let pin = '0704';
let count = 0;
for (i = 1; i <= 4; i++) {
let input = prompt('please make a guess');
if (input !== pin) {
console.log('Sorry that was wrong');
count++;
} else {
console.log('That was correct!')
break;
}
}

With number, input 0704 / 000704 has same value.
It must be a "String".

Related

Find the output using typeof function

I am writing a code. And here I have a problem how can I fix that. I have an input line, it takes a string or a number. So I need to check what is the output and get the answer. I need to give a simple solution. So I can't use functions or something like that.
let input = prompt('Enter your text.');
if (typeof input === "string") {
alert("You have string.");
} else if (typeof input === "number" && input > 30) {
alert("number more than 30");
} else if (typeof input === "number" && input < 30) {
alert("number less then 30");
}
prompt will always return a string.
If you want to check whether the string is composed purely of numerical values, you could use a regular expression:
if (/^[+-]?\d+(?:\.\d+)?$/.test(input)) {
// then it's purely numerical
const num = Number(input.trim());
// perform more operations on the number
} else {
// it's not composed of only numerical characters
}
If you don't want to use a regex, you can use Number alone, but then you'll also include values like Infinity which might not be desirable, and since Number('') gives 0, you'll have to check for that separately:
const num = Number(input);
if (input.trim().length && !Number.isNaN(num)) {
// then it's a number, use num
}
Another approach that I'd recommend is to avoid prompt entirely. Consider using a proper modal instead, such as a form with an input box and a submit button.
In such a case, if you want to require a numeric input, just do:
<input type="number">
I had a similar problem a few weeks ago and this is what I did:
function testNumber(test) {
if (isNaN(test) === false) {
console.log("this is a number");
} else {
console.log("this is not a number");
}
}
testNumber(4); // number
testNumber("4") // number
testNumber("string") // not a number
You can replace "test" for a variable if you don't want to use a function
if (isNaN(myVar) === false) {}
And you may want to add more checks if you want to differentiate between 4 and "4"
You can do
let input = prompt('Enter your text.');
if(isNaN(Number(input))){alert("You have string.")};
if (Number(input) > 30) {
alert("number more than 30");
} else if (Number(input) < 30) {
alert("number less then 30");
}
So it can change all Stringed-numbers to numbers and check if they are number with the isNaN function

Javascript Eval() thinks first value is a function

I am writing a function that will evaluate expressions in an input field and return the sum.
Currently is working but I am running into an error that I just cannot figure out. Here is my code in Plunker.
function linkFunction(scope) {
var PO = 10;
scope.value = PO;
scope.result = '';
scope.Evaluate = function (input) {
if (input.match(/[a-zA-Z]/g) != null) { //to check if user has inputted a letter between a-z, case sensitive.
return alert("You must only use numbers, not letters")
} else if (input.match(/[!"^£$&[{}\]?\\##~<>_'|`¬:;,=]/g) != null) { //to check if user has inputted a special symbol
return alert("You must only use the symbols specified")
} else if (input.match(/\.\d*\.+/g) != null) { //to check if user has inputted a doubled decimal eg 10.2.2
return alert("You can only use 1 decimal point")
} else if (input.match(/\.{2,}/g) != null) {//to check if user has inputted a two decimals eg 10..1
return alert("You cannot put two decimals one after another")
}
// if (input.match(/\d*\(\d\W\d\)/g) != null){
// }
var percentPattern = /[0-9]*\.?[0-9]+%/g;
var expressionResults = input.match(percentPattern);
if (scope.enablePercentage) { //if parameter = 1, then do this code.
if (expressionResults != null) { //if user has entered into the input field
if (expressionResults.length > 1) { //if you user has finished the RegEx (%, is the end of the RegEx, so code will think its the end of the array, therefore you cannot add another %)
return alert("Too many % values");
} else {// user has met all requirements
var percentageValue = parseFloat(expressionResults) * PO / 100;
input = input.replace(expressionResults, percentageValue);
}
}
} else if (expressionResults != null) { //if parameter = 0, then do this code. Parameter is off, but user has entered percentage
return alert("You cannot use %");
}
scope.result = eval(input);
}
}});
If you write 10(5+3) it gives you an error
TypeError: 10 is not a function
Obviously if a user ran this code they would expect to see the value 80.
Eval thinks that 10() is a function.
Does anyone know how to fix this problem. Thanks
eval expects you to pass it JavaScript, not algebra.
If you want to multiply two values together then you must use a Multiplicative Operator.
10 * (5+3)

JAVASCRIPT HELP - code not working

My code isn't working, can someone please tell me what the problem is?
I'm guessing it's the for loop, but I cannot find the problem.
<html>
<body>
<script>
username = prompt("Please enter a your username:");
for (var i = 0; i < username; i++) {
if(isFinite(username.charAt(i))) {
result = true;
document.write("The username consists of one or more numbers." + BR);
}
else {
result = false;
document.write("The username must consist of one or more numbers." + BR);
}
}
</script>
</body>
</html>
You have two problems in your code:
In the for loop, use the length of the variable to establish the stop condition
for (var i = 0; i < username.length; i++)
BR is not defined
Working code: http://jsfiddle.net/f643fr4w/
From the output I can probably assume you just want to check if username consists of at least one number, actually: a digit.
// iterate over the input
for (var i = 0; i < username.length; i++) {
// check if it is a number (not a digit but that's the same here)
if (isFinite(username.charAt(i))) {
result = true;
// The requirement "one or more numbers" is fulfilled,
// we can break out of the loop
break;
}
else {
result = false;
}
// print something according to "result"
if(result === true){
document.write('The username consists of one or more numbers.');
} else {
document.write('The username must consist of one or more numbers.');
}
}
You have to go over the full length of the string to find out if there's no number but not if you want to find out if there is any number in it.
Now, if you want to test if it consists of only digits you have to reword the requirements, they are a bit too ambiguous now.
Additional hints:
you need to check the input, you always have to check user input!
you need to be aware that JavaScript strings are UTF16. Rarely a problem but gets easily one if you iterate over JavaScript strings.
String.charAt() returns a character, not a number. Don't rely on the automatic conversions in JavaScript, you way too easily shoot yourself in the foot if you rely on it but also if you don't, so be careful.
please don't use document.write, use either the console if available or change the text-node of an HTML element.
With these points in mind you may get something like this:
// make a list of digits
var digits = ['0','1','2','3','4','5','6','7','8','9'];
// ask the user for a username
var username = prompt("Please enter a your username:");
// check input
if (username.length === 0) {
console.log('no username given');
} else {
for (var i = 0; i < username.length; i++) {
// indexOf searches for the same type, that's why the digits above
// are strings with quotes around them
if (digits.indexOf(username.charAt(i)) >= 0) {
result = true;
// The requirement "one or more numbers" is fullfilled,
// we can break out of the loop
break;
}
else {
result = false;
}
}
// print something according to "result"
if (result === true) {
console.log('The username consists of one or more numbers.');
} else {
console.log('The username must consist of one or more numbers.');
}
}
The above is one variation of many and could easily give rise to a heated discussion on some forums (not here! Of course not! ;-) ) but I hope it helps.
Use a regex for such shenanigans:
var username = prompt("username plz kk thx");
var result = /[0-9]/.test(username);
document.write("The username " + (result ? "consists" : "must consist") + " of one or more numbers");

JavaScript phone number validation using charCodeAt

I'd like to validate a phone number input using JavaScript to allow only number input. I prefer not to use regex, so I wrote a function like this:
function numberTest(){
for(var i=0;i<phone_number.length;i++){
if(phone_number.charCodeAt(i) >= 48 && phone_number.charCodeAt(i) <=57){
return true;
}else{
return false;
}
}
}
However it does not work. Any ideas why?
This doesn't work because it returns true after the first valid character. Neither branch will get past the first character, so you need to only return if you find an invalid character. Otherwise, if you reach the end without finding an invalid characters, you can finally return true.
Something like:
function numberTest(phone_number) {
for (var i = 0; i < phone_number.length; i++) {
if (phone_number.charCodeAt(i) < 48 && phone_number.charCodeAt(i) > 57) {
return false;
}
}
return true;
}
// Test various values
var testData = ["1234", "12ab", "123451234512345", "a1234123", "123123123a"];
var output = document.getElementById("results");
testData.forEach(function(test) {
var next = document.createElement("li");
next.textContent = numberTest(test);
});
<ul id="results"></ul>
The isNaN() (means is not a number) method will give you the reverted result in a simpler way...
var phone_number = "5511112223";
alert(isNaN(phone_number)); //returns false meaning it is a valid number
phone_number = "55aa1g11d12223";
alert(isNaN(phone_number)); //returns true meaning it is not a number

Compare in real time letter for letter as you type

I'd like to write a code that compares in "real time" the world that the user introduce in an input box with a given word (i.e "house"). When the letter written is correct, the whole word is in blue, when the user introduce a wrong letter the word becomes red.
This is the html:
<input id='inputtype' onkeyup='return validateAsYouType(this);' />
EDIT: Solved! Here is the solution:
<script type="text/javascript" >
function validateAsYouType(inputElementId)
{
var val = inputElementId.value;
var randomWord = "house";
if (val.length <= randomWord.length && val == randomWord.substr(0, val.length)) {
document.getElementById("inputtype").style.color="blue"; // If right, put it in blue
}
else { document.getElementById("inputtype").style.color="red"; // If wrong, put it in red
}
if( val == randomWord)
{
document.getElementById("inputtype").style.color="#339933"; // If right, put it in green
}
}
Check that the typed word is not longer than the given word, and that the typed word so far is the same as the corresponding letters in the given word:
if (val.length <= randomWord.length && val == randomWord.substr(0, val.length))
You would also need an else for the if statement to also change the color when the word is wrong.
Try this,
function validateAsYouType(inputElementId)
{
var val = inputElementId.value;
var randomWord = "house";
var elem = document.getElementById("inputtype");
if( val == randomWord)
{
elem.style.color="#339933"; // If right, put it in green
}
else
{
elem.style.color="blue"; //if wrong, put it in blue
}
}
Not a lot of change from your code, just an else that shows "real time" checking
Test Link
Under the bit that checks to see if the whole word is correct, make character arrays from your words (val and randomword), and then loop through one array comparing the current char with the same numbered char from the other array.
Something like:
for(int i = 0; i <= val.length; i++)
{
if (valArr[i] != randomwordArr[i])
document.getElementById("inputtype").style.color="#990000";
return;
next i;
}
If any are false change the string to red, otherwise leave it the colour it is.

Categories

Resources