Javascript if else condition run time failure - javascript

I have started javascript today. Trying with the very basic and got stuck with If Else loop.
var input = prompt("type your name"); //variable stores the value user inputs
var outout = tostring(input); // the input value is changed to string datatype and stored in var output
alert(output);//supposed to display the value which it doesn't
if(output == "Tiger")
{alert("It is dangerous");
}
Else
{alert("all is well");
}//I only get a blank page
If I omit the line var output = tostring(input) and try to display the alert box with input value I get the alert box. But after that I only get a blank page. The If Else loop doesn't work at all. I am using notepad++. Also checked in Dreamweaver. There is no compile error. What am I doing wrong?
Sorry for such a basic question and thanks for replying.
Regards,
TD

Your line
tostring(input);
Should be
toString(input);
The toString() method has a capital S
Also, your output variable is called "outout". Don't know if that's a typo...
Not only that, your Else should also have a small e. All JavaScript keywords are case sensitive.

You do not have to convert the result of a prompt to a string, it is a string already. And it actually would be
input.toString()
And Else is lowercase, the correct would be else.
So you can use like this
var input = prompt("Type your name");
if (input == "Tiger")
{
alert("Wow, you are a Tiger!");
}
else
{
alert("Hi " + input);
}
Notice that if you type tiger (lowercase) you will end up on the else. If you want to compare a string case insensitive you can do this:
if (input.toLowerCase() == "tiger")
Then even tIgEr will work.

Your code has the following problems:
var input = prompt("type your name");
var outout = tostring(input);
// Typo: outout should be output
// tostring() is not a function as JavaScript is case-sensitive
// I think you want toString(), however in this context
// it is the same as calling window.toString() which is going to
// return an object of some sort. I think you mean to call
// input.toString() which, if input were not already a string
// (and it is) would return a string representation of input.
alert(output);
// displays window.toString() as expected.
if(output == "Tiger")
{alert("It is dangerous");
}
Else // JavaScript is case-sensitive: you need to use "else" not "Else"
{alert("all is well");
}//I only get a blank page
I suspect what you want is this:
var input = prompt("type your name");
alert(input);
if (input === "Tiger") {
alert("It is dangerous");
} else {
alert("all is well");
}

Related

How to create Alert pop up that shows text based on Prompt input type?

I am a beginner experimenting with some basic Javascript.
My goal is to show a (1.) prompt message (requesting a name) followed by an (2.) alert based on the prompt input. If the prompt input is a valid name (string) then an alert box should appear with text "thank you" + name. Else the alert should appear with the text "you didn't enter a valid name".
The 1. prompt message is working, however, the 2. alert message shows me the same text whether i enter a name/text or a number. In other words the alert message is not distinguishing between text string or number and is always showing the text "thank you" + name.
this is my code:
function EnterName() {
var name = prompt("Enter your name here:");
if (typeof name === "string") {
alert("thank you " + name);
} else if (typeof name === "number") {
alert("you didn't enter a valid name");
}
}
console.log(EnterName());
Would appreciate any insights in how to make the alert box show "you didn't enter a valid name" when a number is entered in the prompt box.
Thanks.
Prompt always returns a string, you could try to convert it to a number and then check to see if it NaN's on you which means it's a string. It would be better to use a regexp here though. You may also want to return the name if you are logging it.
function EnterName() {
var name = prompt("Enter your name here:");
var isNum = !isNaN(Number(name));
if (!isNum) {
alert("thank you " + name);
} else {
alert("you didn't enter a valid name");
}
return name;
}
console.log(EnterName());
You always enter strings into prompts. SO you can try to make it a int below and if it succeeds then give an error message otherwise say hello.
function EnterName() {
var name = prompt("Enter your name here:");
if(parseInt(name)) {
alert("you didn't enter a valid name");
}
else if (!parseInt(name)) {
alert("thank you " + name);
}
}
prompt method parameters type are alway String, no matter what you enter, your condition will always true :
//text & defaultText types are String
`prompt(text, defaultText)`
So you need to change your condition. One solution is using regex for example you can change your code to this :
function EnterName() {
var name = prompt("Enter your name here:");
!name.match(/^\d+$/) ?
alert("thank you " + name)
:
alert("you didn't enter a valid name");
}
console.log(EnterName());
Basically !name.match(/^\d+$/) will check if input data is number or not and based on that will show the alert messages.
https://jsfiddle.net/6mxL59k0/1/
So, one thing I want to emphasize is how you are approaching solving this problem. You are looking at your problem thinking, "If I type in a number, this should be false! Why isn't it working?!". The reason why is because prompt will always return a value that is typed to a string. You are looking to see if there is a number or an int depending on the language.
So, we can break this into two problems. See if this guy is a string, see if that string contains a number
The code below shows a great way to do that using two functions
function enterName() { // Javscript functions should always start with a lowercase unless it is a function express and can be invoked using the `new` keyword
var name = prompt("Enter your name here:");
if (!checkIfContainsNumber(name)) {
alert("thank you " + name);
} else { // if f we dont have a number, we have a valid name, otherwise we are invalid!
alert("you didn't enter a valid name");
}
}
So we have our main function, it takes in the promp which always returns a string
// this solves problem 2, seeing if we have a number inside of our string
function checkIfContainsNumber(myString) {
return /\d/.test(myString);
}
enterName();
our second function checkIfContainsNumber solves part 2 of our problem using a regex expression that matches for a digit (d in this case)

Typeof in IF works but ELSE of same statement fails

I'm attempting to create a javascript variable str. The ID idofnet may not exist, if it doesn't I want to ask for a value for str. If it does exist I want to pick it up from the ID. Here is my code...
function ics214button() {
if (typeof $("idofnet").html() === "undefined") {
var str = prompt("Enter a Log number.");
} else {
var str = $("#idofnet").html().trim();
}
if (str =="") {alert("Sorry no net was selected");}
else {alert ("It worked");}
}
When I test this knowing there is no ID = idofnet, I get the prompt to enter a log number. And the rest of the code executes properly.
But when the idofnet does exist and it contains a value, I still get the prompt asking enter a log number. The value is never set in the else condition testing for undefined.
If idofnet contains a value, why is it still asking me as if it were undefined? The var str will always be a number.
Changing the if condition test to this:
if ( $('#idofnet').length ) {
var str = $("#idofnet").html().trim();
} else {
var str = prompt("Enter a Log number.");
}
Solved the problem.

javascript isNaN() function not working?

I have a function to test if a prompt input is a number, like so:
function myFunction()
{
var person = prompt("Please enter your name", "");
if (person != null)
{
if(isNaN(person))
{
document.write("hello " + person + "<br><br>");
}
else
document.write("You gave me a number");
}
else
{
document.write("You didn't answer.<br><br>");
}
}
but every time I enter a number it keeps outputting hello + the number. I've been googling this function for quite some time and it doesn't make sense to me, it seems like it should work. Why is person returning true?
NaN is a special value in Javascript. What isNaN does is check to see if the value passed is equal* to this special value. If you want to check if something is, say, not a stream of numbers, you can use a regular expression:
if (!/^\d+(\.\d+)?/.exec(person)) {
Or parse the value as a number and see if it converts back to the same string:
var n = parseFloat(person);
if (n.toString() !== person) {
*There's a reason that we don't use === but it's outside the scope of this answer.
The isNaN function checks if a value is NaN. NaN is a value that occurs when making operations that require numbers with non-numbers. Please see the documentation.
However the function does not check if the value is of type number. Too check if a value is of type number use the typeof operator
typeof person === 'number'
Your code is the correct way of using the isNaN method. However for anyone else reading this post I have seen a strange anomaly where the documented usage of IsNaN hasn't worked properly and I got around the problem by combining the parseInt method with the IsNaN method. According to the W3c web site (https://www.w3schools.com/jsref/jsref_isnan.asp) the IsNan('123') should return false and IsNan('g12') should return true, but I've seen scenarios where this isn't the case.
If you're having trouble getting the documented methods to work try this code below:
var unitsToAdd = parseInt($('#unitsToAdd').val());
if(isNaN(unitsToAdd)) {
alert('not a number');
$('#unitsToAdd').val('1');
returnVal = false;
}
Alternatively you can try this method which is well tested.
function isNumber(searchValue) {
var found = searchValue.search(/^(\d*\.?\d*)$/);
//Change to ^(\d*\.?\d+)$ if you don't want the number to end with a . such as 2.
//Currently validates .2, 0.2, 2.0 and 2.
if(found > -1) {
return true;
}
else {
return false;
}
}
Hope this helps.

Removing a string return after a function has been processed

I'm a beginner and a student and I'm hoping someone can help me out. I have an assignment where I need the program to be broken up into 3 functions. The first takes a sentence from the user, the second converts the sentence into a new "pig language" depending on the length of each word, and the third displays the results in the console. I have the heart of this program done, but I have a problem with clearing out the return string. Specifically, once the user has gone through all 3 steps, I don't want them to be able to enter into the 3rd part of the program and see the results again. I want them to have to go back to the beginning. Sorry for drawing this out so much, but I'm just not sure of how else to explain it.
Here's my code:
function prog1(){
var userLang = prompt("Type in your sentence");
//If the user enters an empty string
if(userLang == ""){
console.log("You must enter a sentence");
}
//If the user presses cancel
else if(userLang == null){
wantToQuit = true;
}
//If the user enters in a good string
else {
console.log("Thank you, now go to program 2");
been2prog1 = true;
return userLang;
}
}
function prog2(){
//sets newLang = userLang and splits the string
var newLang = prog1Lang.split(" ");
//enters loop to find length of each split word
var x = 0;
for( x = 0; x < newLang.length; x++ ){
//if it's 5 or less words, add -oink
if ((newLang[x].length) <= 5){
newLang[x] += "-oink";
}
//if it's more than 5 words, add -a
else {
newLang[x] += "-a";
}
}
**newLang.join(" ");**
//put the string back together
console.log("String converted");
been2prog2 = true;
return newLang;
}
function prog3(){
var endLang = prog2Lang;
console.log(endLang);
**delete prog2Lang;**
}
I was thinking "delete" might work, as seen above, but I didn't do anything all all. Then I was thinking a Boolean, but I am not sure how to go about doing so. Any help would be much appreciated.
One last thing, I am also stuck on how to join my string back together. Currently it logs it in the console as being a part of the array and separates each word with quotes and a comma. I've looked up the .join(); and I thought it would do the trick, but it doesn't seem to work either. I put it inside of the if else statements in function 2 but, it just freaks out when I do that, so pointers on this issue would also be much appreciated.
Thank you!
Try assigning the newLang.join to itself..
newLang = newLang.join(" ");
I wasn't sure what the other bit was that you were having trouble with was, I was a bit confused.
if all you are trying to do is clear out a string variable then..
prog2Lang = null;
or
prog2Lang = "";
null is a null object and "" is an empty string.
Is that what you were after?

Am I using the isNAN function in JavasScript correctly here?

I've got a form where the user inputs 3 values, which are then calculated. The outputs are displayed again within the form in some "readonly" output boxes. For each input, I want to validate if they are a number, if not, instead of the form showing "NaN" I want to display an error saying, "Please enter a number" (or something like that). Below is the code I am using, which is executed "onkeyup":
function checkforNumber()
{
if (isNaN(sInput || dInput || pInput) == true) {
alert("You entered an invalid character. Please reset the form.");
}
else {
return(false);
}
}
Am I using this function incorrectly? Is there something wrong with the syntax?
Thanks
if (isNaN(sInput) || isNaN(dInput) || isNaN(pInput)) {
alert("You entered an invalid character. Please reset the form.");
}
also make sure that those 3 variables sInput, dInput and pInput are not strings but were obtained by using parseFloat or parseInt methods.
var sInput = parseFloat(document.getElementById('sinput').value);
var dInput = parseFloat(document.getElementById('dinput').value);
var pInput = parseFloat(document.getElementById('pinput').value);
if (isNaN(sInput) || isNaN(dInput) || isNaN(pInput))
This is what I think you intended. You need to pass each value you want to test in to the isNaN function one at a time. Also note that you don't need the == true part, because isNaN returns true or false so the condition will evaluate to the return value.

Categories