Javascript - Going from one switch statement case to a different switch statement - javascript

I'm trying to have a case in a switch statement that jumps into a different switch statement.
In practice, I want the user to type "close page" in a text box and, before the browser closes the page, I want the user to be asked if he is sure about it. Typing "yes" will close the page, and typing "no" will go back to the previous switch statement.
I need to use a switch statement because there are many other things the user can type into the textbox, which generate different feedback.
I used a different textbox for each switch statement, swapping them when necessary, to try to be able to call both functions with the same key.
This is what I have. But it does not work...
Any help?
function SwapDivs(div1, div2) {
d1 = document.getElementById(div1);
d2 = document.getElementById(div2);
if (d2.style.display == "none") {
d1.style.display = "none";
d2.style.display = "block";
} else {
d1.style.display = "block";
d2.style.display = "none";
}
}
function myFunction01() {
var text;
var answers = document.getElementById("myInput01"").value;
switch (answers) {
case "close page":
text = "are you sure?";
SwapDivs('div01', 'div02');
break;
default:
text = "no valid input";
}
document.getElementById("feedback").innerHTML = text;
}
function myFunction02() {
var text;
var answers = document.getElementById("myInput02").value;
switch (answers) {
case "yes":
text = "Why?";
break;
case "no":
text = "Good!";
break;
default:
text = "no valid input";
}
document.getElementById("feedback").innerHTML = text;
}
<p id="feedback"></p>
<div id="div01" style="display:block">
<input id="myInput01" type="text" placeholder="This is TextBox 01." onKeyDown="if(event.keyCode==13) myFunction01();">
</div>
<div id="div02" style="display:none">
<input id="myInput02" type="text" placeholder="This is TextBox 02." onKeyDown="if(event.keyCode==13) myFunction02();">
</div>

You have an extra quote on your first function:
var answers = document.getElementById("myInput01"").value;
It should be:
var answers = document.getElementById("myInput01").value;
I understand the behaviour is:
If user enters any text other than "close page", we give them feedback of invalid input.
If user enters "close page", we ask them if they are sure and change to input 2.
On input 2, if they input yes we say why, if they input no we say good else say no valid input.
If this is expected, the code works for me.
You can run this one below (converted to ES6):
const SwapDivs = (div1, div2) => {
const d1 = document.getElementById(div1);
const d2 = document.getElementById(div2);
if (d2.style.display == "none") {
d1.style.display = "none";
d2.style.display = "block";
} else {
d1.style.display = "block";
d2.style.display = "none";
}
};
const myFunction01 = () => {
let text;
const answers = document.getElementById("myInput01").value;
switch (answers) {
case "close page":
text = "are you sure?";
SwapDivs('div01', 'div02');
break;
default:
text = "no valid input";
}
document.getElementById("feedback").innerHTML = text;
};
const myFunction02 = () => {
let text;
const answers = document.getElementById("myInput02").value;
switch (answers) {
case "yes":
text = "Why?";
break;
case "no":
text = "Good!";
break;
default:
text = "no valid input";
}
document.getElementById("feedback").innerHTML = text;
};
<p id="feedback"></p>
<div id="div01" style="display:block">
<input id="myInput01" type="text" placeholder="This is TextBox 01." onKeyDown="if(event.keyCode==13) myFunction01();">
</div>
<div id="div02" style="display:none">
<input id="myInput02" type="text" placeholder="This is TextBox 02." onKeyDown="if(event.keyCode==13) myFunction02();">
</div>

Related

Can't change radiobuttons display to none again

i got a container with 3 radionbuttons and 2 of the radiobuttons have another radiobuttons next to them but their displays are none . When i click the radiobutton i wanna display the hidden radiobuttons and when i click another radionbutton i want it's display to be none again .
`function showHiddenText()
{
if (document.getElementById("diger").checked) {
const hiddenInput = document.getElementById("hidden-input");
hiddenInput.style.display = "block";
} else if (document.getElementById("diger").checked == false) {
hiddenInput.style.display = "none";
}
}`
It's a simple function i write to do that but else if part is not working . When i display hidden radio buttons they dont disappear ever again.
radionbuttons
hiddenpart
const variables are block scoped. So, in the else if statement hiddenInput is undefined.
Move it above the statements
function showHiddenText()
{
const hiddenInput = document.getElementById("hidden-input");
if (document.getElementById("diger").checked) {
hiddenInput.style.display = "block";
} else if (document.getElementById("diger").checked == false) {
hiddenInput.style.display = "none";
}
}
By the way, you can make it simpler by replacing the else if statement with else:
function showHiddenText()
{
const hiddenInput = document.getElementById("hidden-input");
if (document.getElementById("diger").checked) {
hiddenInput.style.display = "block";
} else {
hiddenInput.style.display = "none";
}
}
Or even more:
function showHiddenText()
{
const hiddenInput = document.getElementById("hidden-input");
if (document.getElementById("diger").checked) {
hiddenInput.style.display = "block";
return true; // you can return anything here
}
hiddenInput.style.display = "none";
return false; // and here (it is not necessary to return here)
}
Make sure your radio buttons have the same name.
Radio buttons with same name are compared to each other.
Add onclick="showHiddenText()" to inputs, then:
html:
<input type="radio" name="btn" id="diger" onclick="showHiddenText()">
<input type="radio" name="btn" onclick="showHiddenText()">
<input type="radio" id="hidden-input">
js:
function showHiddenText() {
if (document.getElementById("diger").checked) {
document.getElementById("hidden-input").style.display = 'block'
}
else{
document.getElementById("hidden-input").style.display = 'none'
}
}

How to compare two variable values?

I am making a password app where you first create a password and save it to a variable. Once the variable has the value, you can enter the password. If the user got it wrong three times, I want to hide the input box and show a message. So far it is working, but it doesn't compare the two variables. Here is my code:
<p id='password'></p>
<input type='password' title='enter your password'>
<input type="submit" onclick='passwords__()'>
<button onclick='savePassword()'>
Save Your New Password
</button>
<script>
var times = 0;
var input = document.getElementsByTagName('input')[0];
var passwords = document.getElementsByTagName('input')[0].value;
var buttons = document.getElementsByTagName('input')[1];
var buttons2 = document.getElementsByTagName('button')[0];
function passwords__() {
times++;
if (times === 3) {
input.style.display = 'none';
document.getElementById('password').innerHTML = 'You can\'t enter your password because you have not enter the right one for three times';
}
if (input.value === passwords) {
alert('You\'re loged in');
}
}
</script>
<script>
function firstCall() {
buttons.style.display = 'none';
}
firstCall();
</script>
<script>
function savePassword() {
buttons.style.display = 'block';
buttons2.style.display = 'none';
}
</script>
When you set var passwords = document.getElementsByTagName('input')[0].value you set password to the value when the page is loaded and not when the save password button is loaded.
You should
put the savePassword function in the same block where you defined the passwords variable
set the value of passwords in the savePassword method.
Your line
var passwords = document.getElementsByTagName('input')[0].value;
is probably running before the button is pressed, so the value isn't being retrieved when the button is pressed - move this line into your passwords__() function.
Also, use
window.onload = function() {
}
to ensure that the document.getElementsByTagName() is running after the function is fully loaded;
window.onload = function() {
var times = 0;
var input = document.getElementsByTagName('input')[0];
var buttons = document.getElementsByTagName('input')[1];
var buttons2 = document.getElementsByTagName('button')[0];
}
function passwords__() {
times++;
let passwords = document.getElementsByTagName('input')[0].value;
if (times === 3) {
input.style.display = 'none';
document.getElementById('password').innerHTML = 'You can\'t enter your password because you have not enter the right one for three times';
}
if (input.value === passwords) {
alert('You\'re logged in');
}
}
Side note: You have a typo in alert('You're loged in'); (loged -> logged)
what you were missing
you were comparing the second input to an empty string because you are running it before the event of clicking
there are some things you can improve here .
password disappears after save
times count to 0 when logged in
var times = 0;
var input = document.getElementsByTagName('input')[0];
var pass1;
var button = document.getElementsByTagName('input')[1];
var buttons2 = document.getElementsByTagName('button')[0];
function passwords__(){
times++;
pass2 = input.value;
if(times === 3 && pass2 !== pass1){
input.style.display = 'none';
document.getElementById('password').innerHTML = 'You can\'t enter your password because you have not enter the right one for three times';
}
console.log(pass1)
if(pass2 == pass1){
alert('You\'re loged in');
times = 0 ;
}
}
function firstCall(){
button.style.display = 'none';
}
firstCall();
function savePassword(){
pass1 = input.value;
input.value = '';
button.style.display = 'block';
buttons2.style.display = 'none';
}
<p id='password'>
</p>
<input type='password' title='enter your password'>
<input type="submit" onclick='passwords__()'>
<button onclick='savePassword()'>
Save Your New Password
</button>

Can anyone plz tell me why in this code the button is not clickable, and how to make it clickable?

I have two text input fields in html and one button. first will take id and second will take password, clicking on button will either display a div saying welcome or a paragraph asking for correct login credentials. the id and password are hard-coded.
Thing is that the submit button is not clickable at all. I don't know what is causing this failure, plz help.
<input type="text" class="id" style="margin-top:10px">
<input type="text" class="pass" style="margin-top:10px">
<button class="enter" style="margin-top:6px; padding:6px; background:orange;">Enter</button>
<p class="loginMsg"></p>
<script>
const idvalue ="Superhero";
const passvalue ="Superzero";
const id = document.querySelector(".id");
const pass = document.querySelector(".pass");
const enter = document.querySelector(".enter");
const para = document.querySelector(".loginMsg");
enter.onclick = function() {
let myid = id.value;
let mypass = pass.value;
if(myid==idvalue && mypass==passvalue) {
let panel = document.createElement("div");
let msgpara = document.createElement("p");
msgpara.textContent="Welcome back "+idvalue;
let btn = document.createElement("button");
btn.textContent = "OK";
panel.appendChild(msgpara);
panel.appendChild(btn);
html.appendChild(panel);
btn.onclick = function(){
panel.parentNode.removeChild(panel);
};
};
else {
para.textContent = "Please enter correct id and password.";
};
};
</script>
Check your code on line 33, you added a semicolon before the else in your if-else statement
if{
...};
else{
};
See https://jsfiddle.net/gfL8jwhq/ for the correction.
Yes due to semicolon(;) after if() condition creating the issue remove it, and it will work properly
enter.onclick = function() {
let myid = id.value;
let mypass = pass.value;
if(myid==idvalue && mypass==passvalue) {
let panel = document.createElement("div");
let msgpara = document.createElement("p");
msgpara.textContent="Welcome back "+idvalue;
let btn = document.createElement("button");
btn.textContent = "OK";
panel.appendChild(msgpara);
panel.appendChild(btn);
html.appendChild(panel);
btn.onclick = function(){
panel.parentNode.removeChild(panel);
};
} else {
para.textContent = "Please enter correct id and password.";
};
};

I want my input to be connected to functions to be validated

Good day everyone,
I want my input to validate this formula
function toCelsius(f) {
return (5/9) * (f-32);
}
So that anytime I change the input number, the answer changes. I tried this function, but I am not getting the required solution.
This is what I tried:
put=toCelsius(value);
if (isNaN(x) ) {
text = "Input is not a number";
} else {
text = toCelsius;
document.getElementById("demo1").innerHTML = put;
}
To make your code work, all you have to do is to use addEventListener and bind an event to your form. So I just made a simple form with input and a submit button, then I will listen to the button click after that I will run your provided function (with a bit modification).
So the final output will be something like this:
const input = document.querySelector("input");
const button = document.querySelector("button");
const message = document.getElementById("message");
button.addEventListener("click", toCelsius);
function toCelsius(event) {
event.preventDefault();
const inputValue = input.value;
const toCelsiusValue = (5 / 9) * (inputValue - 32)
if (isNaN(toCelsiusValue) || !inputValue) {
message.innerHTML = "Input is not a number";
} else {
message.innerHTML = ""
input.value = toCelsiusValue
}
}
<div>
<form>
<input type="text">
<button>Convert</button>
</form>
<p id="message"></p>
</div>

How can i add a picture instead of text in an if or else statement

Hi I have created a HTML and JavaScript website with a conditional statement where it replies something back if you say hi.
function myFunction() {
var letter = document.getElementById("myInput").value.toLowerCase(),
text;
if (letter === "hi im jack") {
text = "Spot on! Good job!";
} else if (letter === "hi" || letter === "hey" || letter === "hello" || letter === "hi there") {
text = "Hi I Am Mike";
}
document.getElementById("demo").innerHTML = text;
}
<input id="myInput" type="text" onkeyup="myFunction()" style="font-size: 30pt; height: 50px; width: 600px;">
<button onclick="myFunction()" style="font-size: 30pt; height: 50px; width: 200px;">ENTER</button>
<p id="demo">result here</p>
The problem is I need to add an image instead of text for one of the replies. I also need to know how to make it send you to a different website automatically. I'm looking for something really simple that can replace the "text ==" if possible.
Use the same code as you used and assign new values to the text variable as follows:
function myFunction() {
var letter = document.getElementById("myInput").value.toLowerCase(),
text;
if (letter === "hi im jack") {
text = '<img src="imageName.jpg" width="200" height="200" />'; //Show an image
} else if (letter === "hi" || letter === "hey" || letter === "hello" || letter === "hi there") {
location.href = 'http://www.websitename.com'; //Redirect automatically
}
document.getElementById("demo").innerHTML = text;
}
Please see this answer, it might help: How to display image with javascript?
Place the following instead of the text line and it should work.
text = ('< img src="+http:xxx+"/>');
You could use a switch statement instead of the if A switch statement is kind of like an if else conditional with some syntactic sugar eg
switch( chackVariable ){
case value:
doSomeStuff()
break; // break will end the switch statement and prevent testing any other cases
}
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/switch
then the other part of the question was relating to creating an image, I would just use innerHTML to create it as a string as has been said here before.
function myFunction() {
// try to save your helper variables at the top of the function
var
input = document.getElementById("myInput"),
demo = document.getElementById("demo"),
letter = input.value.toLowerCase(),
text;
switch( letter ){
case 'hi im jack':
text = 'Spot on! Good Job!';
break;
// you can do && conditions by doing multiple cases for one set of functionality
case 'hi':
case 'hello':
case 'hi there':
text = 'Hi I Am Mike';
break;
case 'image':
text = '<img src="http://lorempixel.com/100/100/" />';
break;
case 'personal space':
// you can redirect the page with js by setting the value for document.location.href
// it wont work on stack however due to the same origin policy and settings on the other web page
document.location.href = 'https://www.youtube.com/embed/2DfmDuOxcN8';
break;
// default will be run if none of the cases match or the previous cases did not have a break
default:
text = 'result here';
}
demo.innerHTML = text;
}
<input id="myInput" type="text" onkeyup="myFunction()" style="font-size:30pt;height:50px;width:600px;">
<button onclick="myFunction()" style="font-size:30pt;height:50px;width:200px;">ENTER</button>
<p id="demo">result here</p>

Categories

Resources