Variable x not working right - javascript

Please help me out guys i have tried to figure this out for ages now. The problem i seem to have is second web page pops up right as the first one does even though it should pop up only after variable x is declared, here is my code try it out and you will see.
<script>
function myFunction()
{
var x;
var r=confirm("By pressing ok you are confirming your username and password");
if (r==true)
{
x="Thank You for Registering!";
}
else
{
x="You pressed Cancel!";
}
document.getElementById("demo").innerHTML=x;
}
var nextpage;
if (x = "Thank You for Registering!"){
window.open('Password.html');
}//end if
</script>
see the problem is that "password.html" is opened right as this page is opened when is should only open after x="thank you for Registering"
Please guys i will be forever grateful if someone figures this one out.

When you do x = "Thank You for Registering!" you are assigning that string to x. After you do the assignment, it tests if the value is "true-ish," which it is. Instead of = (assignment), you want == (comparison).

You are not comparing the variable value correctly. You are doing X= "" which calls assignment not comparison. So for compare a value you need to put this in this way
x == "Thank You for Registering!"
== will do the job. Keep these things in practise.
Learn more here.

'=' is an assignment operator whereas '==' is a comparison operator.
for example.if you write something like this.
if(x=1)//always true
{
}
else //this part will never be executed
{
}
then the above code will always result in true so else part will never be executed,you also are facing the same problem.so
Replace '=' with '=='
if (x == "Thank You for Registering!"){
window.open('Password.html');
}

Related

how can you take out extra space in Javascript?

I'm trying to give a welcome message to recruiters that view my html webpage. The javascript code I'm using is:
function myFunction() {
var person = prompt("Please enter your name", "");
if (person == null) {
var message = document.getElementById("demo").innerHTML =
"Hello! Thank you for viewing my resume.";
message.innerHTML.replace((/\s/g,''));
}
else {
document.getElementById("demo").innerHTML =
"Hello " + person + "! Thank you for viewing my resume.";
}
}
The output in the html looks like Hello ! Thanks for viewing my resume. I've tried flipping the else and if outputs but it still adds the extra space. How can I fix this? I know there are similar questions on stack but the solutions haven't worked in my case. Thanks for your help.
in this case I think you can use Template literals (Template strings), one feature of ES6.
function myFunction() {
const person = prompt("Please enter your name", "");
if (!person) {
const message = document.getElementById("demo").innerHTML =
"Hello! Thank you for viewing my resume.";
message.innerHTML.replace((/\s/g,''));
}
else {
document.getElementById("demo").innerHTML =
`Hello ${person}! Thank you for viewing my resume.`;
}
}
The input would be labeled as Undefined which does not necessarily equal Null in JavaScript. My advice would be try creating a different way to check the name. Perhaps just give them the option "Continue as Guest" instead of checking for an empty value.
message.innerHTML.replace((/\s/g,''));
That line is doing absolutely nothing, replace() returns a new string, it doesn't modify the old one
And even if it replaced the old one, the desired output wouldn't really be what you're looking for, it would remove all spaces in the string, all of them.
The way you remove extra spaces is by using .trim(), trim() removes any extra spaces at the start and/or at the end of the string, so you would do: message.innerHTML = message.innerHTML.trim();
if (person == null) {
This wouldn't work, since prompt would return an empty string if the user didn't provide anything and your explicitly checking if it is equal to null instead, the most "optimal" way for checking for that, is as #Anh Tuan did, if (!person), this works because empty strings, undefined, or null all are falsy, so this is a nice way to check for all of them.
use:
if (!person)
instead of:
if (person == null)
and it should work fine. Everything else can stay the same.

In a series of prompts, need to keep asking the last prompt over and over until answer

I'm creating a joke script for a site that does a series of prompts asking the user if they agree I know javascript. After they answer negative the first time, a slightly modified version of the question is restated. And finally a mocking version of the question is asked and if answered negatively will just ask it again and again until it's answered yes. I can get to the last part just fine. But I can't figure out how to get the code to go back to the last question over and over again and then switch to "thank you" response after they finally are forced to say yes. any help would be appreciated.
my code:
javascriptExample.addEventListener("click", function(){
const answer = prompt("This prompt was created using Javascript. Are you now satisfied we know Javascript? Y/n: ");
if (answer == "n") {
answerTwo = prompt("Sigh. Fine. What about now? Y/n: ");
if (answerTwo = "n") {
do{
const answerThree = prompt("Look, I can do this all day long. So, why don't you knock it off and just go ahead and say yes already, okay? Y/n: ");
} while(answerThree == "n");
} else {
alert("About time. Thank you for your cooperation and vote of confidence. I'm wasn't sure I could've kept it up forever.");
}
} else {
alert("Thanks for the vote of confidence. You're a real mensch!");
}
});
while(["A","B","C"].every(el=>!confirm(el))){}
alert("Fine");
A,B and C are your questions. Just a bit shortified...
If you wanna keep your exact answer structure:
if(confirm("A") || confirm("B")){
alert("nice of you!");
return;
}
while(true){
if(confirm("C")){
alert("youve got it");
return;
}
}
Note that variables defined using an ES6 const or let are block scoped rather than function scoped like variables defined using var.
For this reason, answerThree is no longer is scope inside the while condition and the comparison fails.
Instead, define the variable before the loop:
let answerThree;
do {
answerThree = prompt("Look, I can do this all day long. So, why don't you knock it off and just go ahead and say yes already, okay? Y/n: ");
} while (answerThree == "n");
This will lead to your desired result. Also note that you cannot reassign consts, which is why a let needs to be used here.
switch to "thank you" response after they finally are forced to say yes
This does not seems like a great idea to me because people might feel annoyed and really want to skip this question!
get the code to go back to the last question over and over again
However if you need to ask multiple questions in multiple patters than I would suggest to store questions in an array (a 2D might be more helpful)
var question = {
'1' : {
'1' : 'joke1.1',
'2' : 'joke1.2'
},
'2' : {
'1' : 'joke2.1',
'2' : 'joke2.2'
}
};
question_no=2;
question_version=1
if (answer == "n") {
question_version++;
prompt( question_no[question_no][question_version]+ Y/n: ");
}else{
question_no++;
}

Getting the condition of a while loop to print out once false

I am doing an exercise on an online course to learn Javascript. This is only the first one and I am having issues, so I really want to understand it before I progress.
The question is this:
complete the while loop in the editor so it will print out "I'm learning while loops!". Do this by adding the condition between the parentheses—don't change line 5, or you could get an infinite loop!
The code is:
var understand = true;
while(){
console.log("I'm learning while loops!");
understand = false;
}
I tried adding this to the condition:
while(understand === 0){
But I am getting this error
Oops, try again. It looks like you didn't print the string to the console. Check your loop syntax!
What am I doing wrong in my condition? Could someone please elaborate, so I can learn the key fundamentals to this. Thanks!
The example before this exercise:
var coinFace = Math.floor(Math.random() * 2);
while(coinFace === 0){
console.log("Heads! Flipping again...");
var coinFace = Math.floor(Math.random() * 2);
}
console.log("Tails! Done flipping.");
Edit---update:
You may have noticed that when we give a variable the boolean value true, we check that variable directly—we don't bother with ===. For instance,
var bool = true;
while(bool){
//Do something
}
is the same thing as
var bool = true;
while(bool === true){
//Do something
}
but the first one is faster to type. Get in the habit of typing exactly as much as you need to, and no more!
If you happen to be using numbers, as we did earlier, you could even do:
It's while(understand === true)
Because the loop will fire the first time, as understand is already set to true. Then, as it's firing, it will set understand to false- so the next time it tries to fire the loop the condition will fail and it won't continue. This way, you're getting one execution of the loop- thus printing only one time.
If you had code that looks like this
while(true){
console.log("I'm learning while loops!");
understand = false;
}
you would get an infinite loop! The loop would just keep going because the conditional will always be true. Now if only there were some way, like a variable in the conditional, to make the conditional false.

Command Buttons Not Responding to JS functions

I am very close to finishing this program but am unable to get past one last hurdle. I want some very simple code to execute when the command buttons are pressed. When the Submit Order button is pressed the following code should run to check that the form is completed.
function validateForm()
{
if ($("tax").value = 0)
{
alert ("You have not selected anything to order");
}
if ($("shipCost").value = 0)
{
alert("You must select a method of shipping");
}
}
And when the reset button is pressed the following code should run.
function initForm()
{
$('date').value = todayTxt();
$('qty1').focus();
}
Unfortunately the buttons are not executing the code which I am trying to execute through the following set of functions.
window.onload = function ()
{
initForm();
todayTxt();
productCosts();
shipExpense();
$('shipping').onchange = calcShipping;
calcShipping();
$("Submit Order").onclick = validateForm();
$("reset").onclick = initForm();
}
I have created a fiddle so you can see the full program: http://jsfiddle.net/KhfQ2/ Any help is greatly appreciated.
You're doing it way wrong.
With if statements, you use == instead of =.
= in A = B means assign value of B to A
== in A == B means A equals B
Read about .ready and use it instead of window.onLoad, it's quite a bad choice when it comes to binding, ie.
$( document ).ready(function() {
//taken from api.jquery.com/ready/
});
If you're using jQuery, use # when refering to ID objects, ie.
$('#tax').val();
On no account should you use spaces when giving any object a unique name or class!
Pay attention to letters. You had ".clisk()" instead of "click()".
Check it out and provide us with fixed code.
It is simple. $("Submit Order") doesn't work, because the button doesn't have this id. You can change this to something like $("btn-submit-order"). Same thing to reset.
Moreover, when you test $("tax").value = 0 I think you mistyped = instead of ==.
Other issues...
I think you mean
if ($("#tax").val() == 0)
Note:
Uses the correct selector #
Uses the jQuery val() function. The jQuery object doesn't have a value property.
Compares to 0 using loose checking, though personally I would write the line as
if (+$("#tax").val() === 0)

Javascript "if" statement within alert

I'm new to JavaScript, and I'm wondering how to embed "if" statements within alerts. Specifically, I'm working on a form, and I want the alert that appears after the user clicks "Submit" to display different messages depending on which elements of the user's input are problematic (if any). I know that I could do it the other way around (i.e., use a series of if statements to determine which alert to show), but I was hoping to be able to use "if/else" within the alert code itself. Thanks!
You don't want to use an alert. It's used exclusively to inform the user that something has occurred, and you can't exactly get feedback from it. What you should use instead is a prompt or a confirm. Using the confirm code will allow you to determine whether the user hit OK or Cancel. While this is very limited, it still functions in a manner similar to what you're looking for. For example
var r=confirm("Press a button");
if (r==true)
{
x="You pressed OK!";
}
else
{
x="You pressed Cancel!";
}
Using the prompt code will allow the user to input a value, which you can then append to a variable and use logic from there, such as
var person=prompt("Please enter your name","Harry Potter");
if (person!=null)
{
x="Hello " + person + "! How are you today?";
document.getElementById("demo").innerHTML=x;
}
The standard syntax for the prompt function is
prompt("This text will appear in the alert box","This is the default value");
My source, as well as additional information, is available at W3schools
Edit - I forgot to mention that, if they're using a form you've made in javascript, it could be easier just to run a simple if/else statement that checks if all of the values they've input are not null and have the right datatype before allowing them to continue. Have the else be the alert, I suppose, if you're using the if to confirm validity, as opposed to a lack thereof.
Use a variable:
msg = "";
if (…)
msg = "error 1";
else if (…)
msg = "error 2";
[…]
if (msg.length)
alert(msg);
I was hoping to be able to use "if/else" within the alert code call
You could use the conditional operator, which is basically an else-if inside an expression - which means that the expression as a whole can be passed as an argument:
alert( /* condition */ ? "error 1" : "everything is fine" );
You can write something like
alert(condition ? "Text if true": "text if false");
But it wouldn't be the most readable code. The commented options of
alert(getAlertMessage(anyNeededValue));
or
if (cond) {
alert("true");
} else {
alert("false");
}
sound better. But if you really keen on that "if in the alert", here you have an inline function:
alert((function(){
if (cond) { return "Text when true";}
else {return "Text when false");})());
alert takes a string as an input. Which can come from a variable.
var message;
if ("condition1") {
message = "message1";
} else if ("condition2") {
message = "message2";
} else if ("condition3") {
message = "message3";
}
alert(message);
Unfortunately if is a statement, and can't be directly used as an argument. But you can use the ternary operator instead, which is an expression.
alert(if ("this") { "won't" } else { "work"} );
alert('but' ? 'this' : 'will');
This is also possible, altough I've never seen it used:
alert(
('condition1') ?
'result1' :
('condition2') ?
'result2' :
'result3'
);

Categories

Resources