How to insert an if in a switch case in javascript? - javascript

I have this simple javascript function:
function updateDeleteUser(action, userid) {
frm = document.getElementById("frmsearch");
frm.frmUserId.value = userid;
switch (action) {
case 0:
frm.action = "UpdateUser.jsp";
break;
case 1:
confirm("Delete account?");
if (confirm != false){
frm.action = "DeleteUser.jsp";
}
}
frm.submit();
}
Even if I click on 'NO' the function runs anyway and user gets deleted. What did I do wrong?
Thanks in advance.

You are not doing anything with the return value of the confirm(…) call, instead you use the confirm function itself as the compare value in your if-condition. You want
if (confirm("Delete account?")) {
frm.action = "DeleteUser.jsp";
}
Notice that this has nothing to do with the switch statement.

You are using Confirm Method is wrong position as it always behaves like native function.#
Correct usage is as follows
case 1:
// confirm("Delete account?");
if (confirm("Delete account?") != false){
frm.action = "DeleteUser.jsp";
}

Related

Conditionally adding an object to another object in Javascript

Background
I've been writing a library in Google App Script for my company that sends out an email based on parameters a user assigns. This function is similar to Google's MailApp.sendEmail() function. Building off of that function, I've been working on a way that allows a user to take a sheet from a spreadsheet and send that as a PDF in the email as well. This is determined through an object {sheet: 'sheet to be PDF', name: 'PDF name', type: 'portrait'}, with the sheet key determining which sheet will be converted and sent as a PDF, name key determining the name of the PDF, and type key being whether the PDF is sent out in either portrait or landscape mode. An example of what this function call would look like is: sendEmail('person#gmail.com', 'subject', 'body', 'otherperson#gmail.com', {sheet: 'sheet1', name: 'PDF_name', type: 'landscape'}. So in this case, an email will be sent to the email address person#gmail.com with otherperson#gmail.com being cc'd to the email. The email that is sent, the subject line will read as subject, with the body of the email only saying body. The object at the end does something further. If your code is attached to a spreadsheet, it will locate the sheet with the name sheet1, convert that into a PDF, setting the name of the newly created PDF as PDF_name and setting that PDF in landscape mode.
I have it set up so that if someone wants to send a sheet as a PDF, but they do not specify what they want the name of the PDF to be set to or type of orientation they want the PDF to be in, then the name of the PDF will just be the sheet name and the type will just be portrait mode. The issue that arises is in a switch-case statement, specifically this one:
Assumed Problem Code
if(arguments.length >= 4){
switch(true){
case validateEmail(arguments[3]):
options.cc = arguments[3]
case (isObject(arguments[3]) && arguments.length === 4)|| isObject(arguments[4]):
options.pdf = {
sheet: arguments[3].sheet,
name: arguments[3].name,
type: arguments[3].type
}
tempName(options)
}
}
My understanding of how switch-case statements work is when the switch argument is set to true, it will only execute the specific case if the argument/value/whatever returns true. An example case where it keeps failing is when the function is called, the arguments are sendEmail('person#gmail.com', 'subject', 'body', 'otherperson#gmail.com').
In my example, since there are 4 arguments, it should run through the switch-case, and should return true for the first case, as it is an email. It would then proceed to the next case because there is no break after the first case. However, it should return false because the email will not be an object, but a string. The issue is that even though it does not pass that case, it still creates the object and adds it to the options object that was created earlier in the script. I'm not sure why this is happening, as not passing that case shouldn't create that object, and shouldn't then proceed to the tempName() function call. Any assistance or advice is appreciated. I will also link all of the remaining relevant code below:
This is not relevant to the issue, but I should explain it as well. The tempName() function call is just for checking when a user IS adding the object, it checks if those values are null. It then sets them to default parameters so the PDF will have the same name as the sheet being converted into a PDF and type of PDF will be portrait mode. It then proceeds to another function call that converts it into a PDF properly.
Relevant Code
function sendEmail(){
try{
const options = {
to: arguments[0],
subject: arguments[1],
body: arguments[2],
}
if(arguments.length >= 4){
switch(true){
case validateEmail(arguments[3]):
options.cc = arguments[3]
case (isObject(arguments[3]) && arguments.length === 4)|| isObject(arguments[4]):
options.pdf = {
sheet: arguments[3].sheet,
name: arguments[3].name,
type: arguments[3].type
}
tempName(options)
}
}
function tempName(options){
Logger.log(options)
switch(true){
case options.pdf.name == null:
options.pdf.name = options.pdf.sheet
case options.pdf.type == null:
options.pdf.type = 'portrait'
}
return options.attachments = [pdf(options.pdf.sheet, options.pdf.type).setName(options.pdf.name)]
}
MailApp.sendEmail(options)
} catch(e){
Logger.log(e)
}
}
Other Potentially Relevant Code
The PDF converter function
function pdf(sheetName, type){
let ss_id = spreadsheet.getId()
let sheet_id = spreadsheet.getSheetByName(sheetName).getSheetId()
let url
//Check for type submitted
switch(type){
//Spreadsheet converted to PDF in portrait mode
case 'portrait':
url = "https://docs.google.com/spreadsheets/d/" + ss_id + "/export?format=pdf&gid=" + sheet_id
break
//Spreadsheet converted to PDF in landscape mode
case 'landscape':
url = "https://docs.google.com/spreadsheets/d/" + ss_id + "/export?format=pdf&portrait=false&gid=" + sheet_id
break
//If neither option works, then user did no enter 'portrait' or 'landscape' as their type option
default:
throw `${type} is not a valid PDF format`
}
let response = UrlFetchApp.fetch(url, {
muteHttpExceptions: true,
headers: {
Authorization: 'Bearer ' + ScriptApp.getOAuthToken(),
},
}).getBlob()
return response
}
The email validator function. I cannot use APIs currently, so this is my current workaround to validate if an email exists.
function validateEmail(email){
let ss = SpreadsheetApp.openByUrl(SpreadsheetApp.create('Email Validation Spreadsheet', 1, 1).getUrl())
if(!new RegExp('[#]').test(email)){
return false
} else{
try{
ss.addViewer(email)
} catch(e){
setTrashed()
return false
}
setTrashed()
return true
}
function setTrashed(){
DriveApp.getFilesByName('Email Validation Spreadsheet').next().setTrashed(true)
}
}
Checker to make sure something is an object
//Checker to make sure an object is an object
function isObject(obj){
if(obj != null && obj.constructor.name === 'Object'){
return true
} else{
return false
}
}
Suggestion: Replace the Switch Statements (with Issues) with If Statements
You can achieve the concept you wanted for your switch statements with if statements since the current switch statement that you use is not applicable in this case.
Script:
Based on your post, you can replace the part of your script from:
if (arguments.length >= 4) {
switch (true) {
case validateEmail(arguments[3]):
options.cc = arguments[3]
case (isObject(arguments[3]) && arguments.length === 4) || isObject(arguments[4]):
options.pdf = {
sheet: arguments[3].sheet,
name: arguments[3].name,
type: arguments[3].type
}
tempName(options)
}
}
To:
if (arguments.length >= 4) {
if (validateEmail(arguments[3]))
options.cc = arguments[3];
if ((isObject(arguments[3]) && arguments.length === 4) || isObject(arguments[4])) {
options.pdf = {
sheet: arguments[3].sheet,
name: arguments[3].name,
type: arguments[3].type
};
tempName(options);
}
}
Additional Analysis:
Let me present some test cases with their corresponding output.
Switch Statement with Break Statements
function test1() {
var data = 7;
switch (true) {
case (data < 5):
console.log("Less than 5");
break;
case (data < 10):
console.log("Less than 10");
break;
case (data > 5):
console.log("Greater than 5");
break;
case (data > 10):
console.log("Greater than 10");
break;
}
}
From this, the expected output should like the one below which is lacking:
This is the basic concept of switch statements wherein only the case which first matched with the switch expression is executed and then terminate the whole switch statement because of the break statement.
Switch Statement without Break Statements
function test2() {
var data = 7;
switch (true) {
case (data < 5):
console.log("Less than 5");
case (data < 10):
console.log("Less than 10");
case (data > 5):
console.log("Greater than 5");
case (data > 10):
console.log("Greater than 10");
}
}
From this, the expected output should be the one below which included an incorrect output:
Proposed Solution: Multiple If Statements
function test3() {
var data = 7;
if (data < 5) {
console.log("Less than 5");
}
if (data > 5) {
console.log("More than 5");
}
if (data < 10) {
console.log("Less than 10");
}
if (data > 10) {
console.log("More than 10");
}
}
From this, the expected output should look like the one below which should be just right:
Reference:
JavaScript Switch Statement

How to go to an a Specific HTML when a word is detected (Java)

Java I made an HTML called hello.html and now I want to use the replace() function in Java to go to the HTML page when the word "Covid" is detected on Google, I tried but it doesn't work for some reason, can you see where I am going wrong, or do I have to change my entire code?
function redirectURL() {
var specWord = getSpecificWord();
switch(specWord)
{
case 'corona':
window.location.replace('hello.html');
break;
case 'covid':
window.location.replace('hello.html');
break;
case 'covid-19':
window.location.replace('hello.html');
break;
default:
return true;
break;
}
return false; // don't let the form submit
}
function getSpecificWord(Element) {
var specificWord = "corona";
return specificWord;
}
The code does not work since you are not calling the redirectURL function.
Append redirectURL() to your code or use this instead:
(function redirectURL() {
var specWord = getSpecificWord();
switch (specWord) {
case 'corona':
window.location.replace('hello.html');
break;
case 'covid':
window.location.replace('hello.html');
break;
case 'covid-19':
window.location.replace('hello.html');
break;
default:
return true;
break;
}
return false; //don't let the form submit
})();
function getSpecificWord(Element) {
var specificWord = 'corona';
return specificWord;
}

Validate forms using javascript

I want to validate 3 inputs (name, email and password) in a form using javascript. When the user submits the form, and all the fields are empty, it works correctly showing the error messages. But then if I write a correct password (length 7) and wrong email and name, and I try to submit the form again the "Password too short" message is stil there and the password is correct. What I am doing wrong?
Javascript file
function verify(){
if(verName()&verEmail()&verPassword())
{
return true;
}else
{
verName();
verEmail();
verPassword();
return false;
}
}
function verPassword(){
var ok = true;
var frm = document.getElementById("register");
var pass = frm.elements[2].value;
if(pass.length<6)
{
var text="Password too short";
document.getElementById('textPassword').innerHTML=text;
ok = false;
}
return ok;
}
HTML file
<form id='register' name='register' onsubmit="return verify()">
function verify(){
document.getElementById('textPassword').innerHTML = ' ';
if(verName()&verEmail()&verPassword())
{
return true;
}else
{
verName();
verEmail();
verPassword();
return false;
}
}
change your code it like this:
function verify(){
if(verName()&verEmail()&verPassword())
{
return true;
}
else
{
if(verName());
if(verEmail());
if(verPassword());
return false;
}
}
with this solution, each validation occurs if the previous validation runs true! and if not, just the previous validation errors shows up !
in each function verName(), verEmail() and verPassword(), return Boolean value of TRUE of FALSE
also add this line of code, on your form submit event:
verify() {
document.getElementById('textPassword').innerHTML= ' '
....
....
}
The problem is that your verPassword function is adding that error string when the password is invalid, but it doesn't remove it when the password is valid.
Also, your verify function makes little sense.
How about:
function verify(){
return verName() && verEmail() && verPassword();
}
function verPassword(){
var frm = document.getElementById("register");
var pass = frm.elements[2].value;
var ok = pass.length > 5;
var text = ok ? "" : "Password too short";
document.getElementById('textPassword').innerHTML=text;
return ok;
}
You have to empty the #textPassword element by write something like: document.getElementById('textPassword').innerHTML.
In addition I can see some wrong codes there. First, if every ver* function returns true or false, you better use && rather than & in if condition expression. Or you can just return the evaluated value of the condition expression like this: return verName() && verEmail() && verPassword().
Second, the ver* functions are already called while if evaluate condition expression. No need to call those functions again in else part.
And I don't think you need ok variable in verPassword() function.
I suggest to change the code like below:
function verify(){
return verName() && verEmail() && verPassword();
}
function verPassword(){
var frm = document.getElementById("register");
var pass = frm.elements[2].value;
var textPassword = document.getElementById('textPassword');
if (pass.length < 6) {
var text="Password too short";
textPassword.innerHTML = text;
return false;
} else {
textPassword.innerHTML = ""; // Empty #textPassword
return true;
}
}

Can I implement/put an array on a switch conditional?

I was building my code when came to my mind a bizarre idea, can I implement/put an array inside a switch?
I mean, how can I make the codeHide case work? with this piece of code it don't work.
When I ask to set the command and I put hide() (that is codeHide[0] on the codeHide array) I want to switch take the codeHide case (my if-statement) and return an alert telling me the alertMessage of that particular array element.
If I put hide(background) (that is codeHide[1] on the codeHide array) I want to switch take the codeHide case else (of my if-statement) and return an alert telling me the alertMessage of that particular array element(in the is-statement).
Hope you understand me.
Doing this it don't work and I think it's because the "case codeHide:".
And this is what I've done so far:
var codeHide = ['hide()', 'hide(background)'];
$(".code").on("click", function () {
var codePrompt = prompt("Set the code in the command line."),
alertMessage = "",
consoleMessage = "Used '" + codePrompt + "' command.";
switch (codePrompt) {
case codeHide:
if (codeHide[0]) {
alertMessage = "Hiding elements...";
} else {
alertMessage = "Hiding Background...";
}
break;
default:
alertMessage = consoleMessage = "We are sorry but you entered a WRONG command, try again tho!\ntyped: " + codePrompt;
break;
}
alert(alertMessage);
console.log(consoleMessage);
});
I think you are trying something like
var commands = {
hide: 'hide()',
hideBg: 'hide(background)'
};
var codePrompt = prompt("Set the code in the command line."),
alertMessage;
switch (codePrompt) {
case commands.hide:
alertMessage = "Hiding elements...";
break;
case commands.hideBg:
alertMessage = "Hiding Background...";
break;
default:
alertMessage = "WRONG command";
break;
}
}
However, you can also use
var commands = {
'hide()': "Hiding elements...",
'hide(background)': "Hiding Background..."
};
var codePrompt = prompt("Set the code in the command line.");
var alertMessage = commands[codePrompt] || "WRONG command";
I guess you also want to run some functions:
var commands = {
'hide()': {
text: "Hiding elements...",
funcion: someFunctionToHide
},
'hide(background)': {
text: "Hiding Background...",
funcion: someFunctionToHideBackground
}
};
var codePrompt = prompt("Set the code in the command line."),
command = commands[codePrompt];
if(!command) {
alertMessage = "WRONG command";
} else {
alertMessage = command.text;
command.function();
}
switch operates by comparing the value being switched on to each of the possible cases using the identity operator ===. This means that you can put an array inside a case, and it will work as specified (but certainly not very intuitively for arrays):
var x = [1];
var a = [1];
switch (x) {
case [1]: alert("it's [1]!"); break;
case a: alert("it's a!"); break;
case x: alert("it's x!"); break;
}
This will alert "it's x!", while you might be expecting that either of the preceding two cases would be "good enough" to trigger. But that's just how === works:
[1] === x // false
a === x // true
x === x // true
So while you can technically use an array, in practice it would be very unusual to have a situation where it's actually useful to do so.
Going back to your code, since the values you are interested in are strings it seems that using a simple object as a map would do just fine:
var commands = {
"hide()": {
alert: "Hiding elements...",
console: "Blah blah"
}.
"hide(background)": {
alert: "Hiding background...",
console: "Blah blah"
}.
};
var fallback = {
alert: "Sorry, wrong command",
console: "Sorry, wrong command"
};
which would then allow you to write
var result = commands[input] || fallback;
alert(result.alert);
console.log(result.console);

Prompt JavaScript If Else Unexpected Token else

I'm teaching myself JavaScript using Code Academy and I'm trying to make some simple code so that when prompt asks a question, the user reply gives a response.
example.
prompt says "what's your favourite colour?"
user says "blue"
response "that's the same colour as the sky!"
But when I try to add different options, I get Syntax error: unexpected token else.
I tried making it so that if I asked a question, the reply gets a response but anything else gets a response.
Here's the code.
prompt("what do you want?");
if ("coke");
{console.log ("no coke, pepsi.")};
else
console.log ("pepsi only.")};
If anyone has any ideas, I'd be very grateful!
Disclaimer: I don't work for Coca Cola.
You need to save the return value of prompt if you want to use it later. Also, you have some syntax errors that should be corrected:
var answer = prompt('what do you want?');
if (answer === 'coke') {
console.log('you said coke!');
} else {
console.log('why didn\'t you say coke!?');
}
You could also use a switch as you get more cases:
var answer = prompt('what do you want?');
switch (answer) {
case 'coke':
console.log('you said coke!');
break;
default:
console.log('why didn\'t you say coke!?');
break;
}
Or an object, as most people prefer this to switch:
var answer = prompt('what do you want?');
var responses = {
coke: 'you said coke!',
defaultResponse: 'why didn\'t you say coke!?'
};
console.log(responses[answer] || responses.defaultResponse);
The if does not need a semicolon at the end. Instead do:
if ("coke") {
console.log ("no coke, pepsi.");
} else {
console.log ("pepsi only.");
}
Remove the trailing semicolons:
prompt("what do you want?");
if ("coke") {
console.log ("no coke, pepsi.");
} else {
console.log ("pepsi only.");
}
You have a semi-colon after the close brace. Try:
var ans = prompt("what do you want?");
if (ans == "coke") {
console.log ("no coke, pepsi.");
} else {
console.log ("pepsi only.");
}
var name = prompt("what do you want?");
if (name == "coke")
{
console.log ("no coke, pepsi.")
}
else
{
console.log ("pepsi only.")
}
Like above
Actually DO NOT do
if (ans == "whatever") {
console.log ("whatever");
} else {
console.log ("whatever.");
}
DO
if (ans == "whatever") {
confirm ("whatever");
} else {
confirm ("whatever.");
}
A variable needs to be identified. Also the bracketing and the semi colons between the "if" "else" statements are problematic. I am not sure about the console log, but if you want a popup alert try this:
var brand = prompt ('what do you want?');
if (brand="coke") {
alert ("no coke, pepsi.")
}else {
alert ("pepsi only.")
};
DICLAIMER: I am novice at best, jut happened to debug a similar issue.
Hope it helps.

Categories

Resources