If statements and conditions - javascript

I am trying to confirm two different things in an alert box, if statement. The first is that the user pressed the yes button and the second is a user input value on the page. See the code below. I'm still pretty green, any help would be greatly appreciated.
var cMsg = "You are about to reset this page!";
cMsg += "\n\nDo you want to continue?";
var nRtn = app.alert(cMsg,2,2,"Question Alert Box");
if(nRtn == 4) && (getField("MV").value == 5)
{
////// do this
}
else if(nRtn == 4) && (getField("MV").value == 6)
{
/////then do this
}
else if(nRtn == 4) && (getField("MV").value == 7)
{
/////then do this
}
}
else if(nRtn == 3)
{
console.println("Abort the submit operation");
}
else
{ //Unknown Response
console.println("The Response Was somthing other than Yes/No: " + nRtn);
}

Your if...else syntax is incorrect. Correct syntax
if (condition)
statement1
[else
statement2]
Use correct syntax
if (nRtn == 4 && getField("MV").value == 5) {
////// do this
} else if (nRtn == 4 && getField("MV").value == 6) {
/////then do this
} else if (nRtn == 4 && getField("MV").value == 7) {
/////then do this
} else if (nRtn == 3) {
console.println("Abort the submit operation");
} else { //Unknown Response
console.println("The Response Was somthing other than Yes/No: " + nRtn);
}
instead of
if (nRtn == 4) && (getField("MV").value == 5) {
////// do this
} else if (nRtn == 4) && (getField("MV").value == 6) {
/////then do this
} else if (nRtn == 4) && (getField("MV").value == 7) {
/////then do this
} <=== Remove this
} else if (nRtn == 3) {
console.println("Abort the submit operation");
} else { //Unknown Response
console.println("The Response Was somthing other than Yes/No: " + nRtn);
}

you are trying to evaluate two different conditions that is:
"nRtn" // value returned from app.alert(cMsg,2,2,"Question Alert Box");
and: getField("MV").value.
However, the compiler will only process the first condition because the braces end there. You should make sure to enclose all conditions within one brace. Individual conditions can and by convention should be in separate braces too within the main brace.
The right way therefore should be:
if ((nRtn == 4) && (getField("MV").value == 5))
//notice the initial if (( and terminating ))
//You could have 3 conditions as follows
// if (((condition1) && (condition2)) && (condition3)))
{
////// do this
}
else if((nRtn == 4) && (getField("MV").value == 6))
{
/////then do this
}
else if((nRtn == 4) && (getField("MV").value == 7))
{
/////then do this
}
}
else if(nRtn == 3)
{
console.println("Abort the submit operation");
}
else
{ //Unknown Response
console.println("The Response Was somthing other than Yes/No: " + nRtn);
}

Related

If else condition not working for string comparision in JS [duplicate]

This question already has answers here:
Check variable equality against a list of values
(16 answers)
Closed 1 year ago.
I have an if-else condition in js as below and I am expecting else condition to execute for the below logic, because the destination ID is in else if, but it always goes into the if condition. tried with == and === too.
What am I missing?
Note: The logic is to be supported in ie11
// destinationId is generated dynamically but i have assigned it to a variable for reference
Code 1
var fromId = "createNotification";
var destinationId ="detailedDescription";
if ((fromId == "createNotification") && (destinationId == "carNumber" || "setNumber")) {
//logic to execute
} else if ((fromId == "createNotification") && (destinationId == "faultRepBy" || "detailedDescription")) {
//logic to execute
}
code 2
if ((["createNotification"].indexOf(fromId) > -1) && (["carNumber" || "setNumber"].indexOf(destinationId) > -1)) {
//logic to execute
} else if ((["createNotification"].indexOf(fromId) > -1) && (["faultRepBy" || "detailedDescription"].indexOf(destinationId) > -1)) {
//logic to execute
}
Change your condition as below:
if ((fromId == "createNotification") && (destinationId == "carNumber" || destinationId == "setNumber")) {
console.log("in if")
} else if ((fromId == "createNotification") && (destinationId == "faultRepBy" || destinationId == "detailedDescription")) {
console.log("in else if")
}

if statement executes code under wrong condition

I have a simple code with a if statement as follows:
if ((marker.category == str || $("#type").length === 0)
&& (marker.session == session || session.length === 0)) {
marker.setVisible(true);
console.log("session"+session);
} else if (marker.session == session || session.length === 0) {
marker.setVisible(true);
} else {
marker.setVisible(false);
infowindow.close(map, marker1);
}
If I run this code, it always executes the else if condition, but I think the if and else if conditions are different, how to solve this problem? I know the if and else if may have a part of same conditions but with operator && it should be different, right? It has really confused me.
It's quite odd to repeat part of a logical AND in an else if condition. I feel you may be able to understand this better if you refactor the common parts out.
For example
if (marker.session == session || session.length === 0) {
marker.setVisible(true); // same for first two conditionals
if (marker.category == str || $("#type").length === 0) { // &&
console.log("session", session);
}
} else {
marker.setVisible(false);
infowindow.close(map, marker1);
}
If you don't see that console.log(), it clearly means the
marker.category == str || $("#type").length === 0
expression is evaluating as false.
You could even simplify this further by re-using the same boolean values where required. This can eliminate the else blocks which can aid readability. I also think it's odd to conditionally log something so just log it anyway.
let sessionVisible = marker.session == session || session.length === 0
marker.setVisible(sessionVisible)
console.log("session", session);
if (!sessionVisible) {
infowindow.close(map, marker1);
}
if (marker.session == session || session.length == 0) {
marker.setVisible(true);
if (marker.category == str || $("#type").length == 0) {
console.log("session"+session);
} else { }
} else {
marker.setVisible(false);
infowindow.close(map, marker1);
}
this is solved, with this code
if ( (marker.session == session || session.length === 0) && (marker.category == str)){
marker.setVisible(true);
}else if( (marker.session == session || session.length === 0) && (str.length === 0)){
marker.setVisible(true);
}else {
marker.setVisible(false);
infowindow.close(map, marker1);
}
}
that is seem like same condition but different, thanks for you all to help me

do while doesn't work

I'm building a website but a JavaScript part doesn't work.
Look here the script:
do {
if (percen === 0) {
console.log();
} else if (percen === 1) {
document.getElementById("percen").innerHTML = "Text"
} else if (percen === 2) {
document.getElementById("percen").innerHTML = "Text"
} else if (clicks === 3) {
++percen;
} else if (clicks === 4) {
++percen;
} else if (clicks === 5) {
++percen;
} else if (clicks === 6) {
++percen;
} else if (clicks === 7) {
var percen = 0;
}
}
But when I run it in a HTML file it will not loop. The var "percen" will ++ when you use a button.
Try adding the 'while' portion of the 'do while' loop at the end:
do {
if (percen === 0) {
console.log();
}
// rest of your code
// ...
}
while (percen < 100);
You forgot the condition at the end.. It is while(condition) remember that the condition is checked at the end of the script so it will enter 1 time. If you want you can do a while syntax while(cond){yourscript}

JS in page head section isn't excecuting

I have a script that handles a semi-complex contact form. The site is built using a website building platform called Duda and I think there may be timing issues as they load a bunch of scripts of their own. Anyway I'm getting a ReferenceError: price is not defined, error.
Price gets called onChange on inputs, for example:
<input value="Yes" name="dmform-9" type="radio" id="watch-me-hide" checked="checked" onchange="price()"/>
The script works sometimes, then other times not. Very frustrating. Does anyone know how to make sure that my functions get loaded in this situation?
Here is the whole script:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
var counter = 0;
$(document).ready(function() {
$("input[type="radio"]").click(function() {
alert("here");
var ids = ["#occupiedBy", "#nameOccupied", "#phoneOccupied", "#mobileOccupied", "#emailOccupied"];
if($(this).attr("id") == "watch-me-hide" || $(this).attr("id") == "watch-me-show") {
if ($(this).attr("id") == "watch-me-hide") {
$("#show-me").hide();
ids.forEach((id) => $(id).prop("required", false));
}
else if ($(this).attr("id") == "watch-me-show"){
$("#show-me").show();
ids.forEach((id) => $(id).prop("required", true));
}
else {
}
} else if($(this).attr("id") == "hideShowInDepth-hide" || $(this).attr("id") == "hideShowInDepth-show") {
if ($(this).attr("id") == "hideShowInDepth-hide") {
$("#moreRooms").hide();
price(null);
ids.forEach((id) => $(id).prop("required", false));
}
else if ($(this).attr("id") == "hideShowInDepth-show"){
$("#moreRooms").show();
price(null);
ids.forEach((id) => $(id).prop("required", true));
}
}
else{
}
});
};
function price() {
var priceIncrement = 70;
var minimumPrice = "189.00";
var basic = document.getElementById("hideShowInDepth-hide");
var advanced = document.getElementById("hideShowInDepth-show");
var ids = ["numberAdditionalRooms", "numberLaundries", "bedrooms", "numberLounges", "numberDining", "numberKitchens", "numberBathrooms", "numberHallways", "numberGarages"];
if ((basic.checked == true) && (advanced.checked == false)) {
/* Get number of rooms for basic inspection */
var e = document.getElementById("bedrooms");
var numberOfBedrooms = e.options[e.selectedIndex].value;
if (numberOfBedrooms == 0){
document.getElementById("totalPrice").textContent = "0.00";
}
else if ((numberOfBedrooms <= 3) && (numberOfBedrooms >= 1)){
document.getElementById("totalPrice").textContent = minimumPrice;
}
else if ((numberOfBedrooms <= 6) && (numberOfBedrooms >= 3)){
document.getElementById("totalPrice").textContent = "259.00";
}
else if (numberOfBedrooms > 6){
document.getElementById("totalPrice").textContent = "329.00";
}
else {
alert("Script error: Undefined number of bedrooms")
}
return false;
}
else if ((basic.checked == false) && (advanced.checked == true)) {
/* Get number of rooms for advanced inspection */
ids.forEach(logArrayElements);
if (counter == 0){
document.getElementById("totalPrice").textContent = "0.00";
}
else if (counter == 1){
document.getElementById("totalPrice").textContent = minimumPrice.toFixed(2);
;
}
else {
var money = ((counter * priceIncrement) + +minimumPrice) - +priceIncrement;
document.getElementById("totalPrice").textContent = money.toFixed(2);
}
counter=0;
return false;
}
else if ((basic.checked == false) && (advanced.checked == false)) {
alert("Script error: Neither checkbox is checked");
return false;
}
else if ((basic.checked == true) && (advanced.checked == true)) {
alert("Script error: Both checkboxes are checked");
return false;
}
else{
alert("Script error: Unknown error");
return false;
}
}
function logArrayElements(element, index, array) {
// alert("a[" + index + "] = " + element + " - " + value);
var e = document.getElementById(element);
var strUser = e.options[e.selectedIndex].value;
counter = +counter + +strUser;
}
</script>
watch-me-hide and watch-me-show are radio buttons that when changed they hide or show another section of the contact form to fill out, and make the inputs required or not.
hideShowInDepth-hide and hideShowInDepth-show are the same, but for another div section.
the price function updates the text in a span to reflect a new price when an input value has changed.
price() gets called onchange of dropdowns and radio buttons.
Any help appreciated.

Why are there "undefined" terms where the outputs are supposed to go to?

The output should look like "Tuesday, July 26, 2016", and then "enjoy" But instead, it looks like
"Tuesday
July
undefined,undefined 26 , 2016
Tuesday"
Here is my code:
var today = new Date();
function getMonth1(today) {
if(today.getMonth() == 0) {
console.log("January");
}
else if(today.getMonth() == 1) {
console.log("February");
}
else if(today.getMonth() == 2) {
console.log("March");
}
else if(today.getMonth() == 3) {
console.log("April");
}
else if(today.getMonth() == 4) {
console.log("May");
}
else if(today.getMonth() == 5) {
console.log("June");
}
else if(today.getMonth() == 6) {
console.log("July");
}
else if(today.getMonth() == 7) {
console.log("August");
}
else if(today.getMonth() == 8) {
console.log("September");
}
else if(today.getMonth() == 9) {
console.log("October");
}
else if(today.getMonth() == 10) {
console.log("November");
}
else if(today.getMonth() == 11) {
console.log("December");
}
}
function getWeekday(today) {
if(today.getDay() == 0) {
console.log("Sunday");
}
else if(today.getDay() == 1) {
console.log("Monday");
}
else if(today.getDay() == 2) {
console.log("Tuesday");
}
else if(today.getDay() == 3) {
console.log("Wednesday");
}
else if(today.getDay() == 4) {
console.log("Thursday");
}
else if(today.getDay() == 5) {
console.log("Friday");
}
else if(today.getDay() == 6) {
console.log("Saturday");
}
}
function getDate1(today) {
console.log(getWeekday(today) + "," + getMonth1(today), today.getDate(), ",", today.getFullYear());
if(getWeekday(today) == "Tuesday") {
console.log("enjoy");
}
}
getDate1(today);
As well as having to return a value as Jaromanda X mentions, you could streamline your code a great deal like this (an array lookup, as Touffy mentions):
function getWeekDay(index) {
return
["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][index];
}
Then use getDay() to call it:
alert(getWeekDay(new Date().getDay()));
Then do the analogous setup for the months, using getMonth() to call it.

Categories

Resources