Javascript / JQuery if Statement not working - javascript

Purpose of the code shown is to add by time some reminder. the cases are for different days of the week and in that days specific times.
Strange thing some statements are working most not, but i dont see what breaks the code:
function refreshTime() {
var now = getTime();
$('#date').html(now.day + ', ' + now.date + '. ' + now.month);
$('#time').html("<span class='hour'>" + now.hour + "</span>" + "<span class='minute'>" + now.minute + "</span>" + "<span class='second'>" + now.second + "</span>");
if (now.day != "Sonntag" && now.day != "Samstag")
{
if (now.hour == "9" && now.minute >= "50")
{
var left = "60" - now.minute;
$('#gh').html("<span class='gh_remind'>Grosshandel einstellen in " + left + " Minuten!</span>");
}
if (now.hour == '11' && now.minute >= '50')
{
var left = '60' - now.minute;
$('#gh').html("<span class='gh_remind'>Grosshandel einstellen in " + left + " Minuten!</span>");
}
if (now.hour == '14' && now.minute >= '50')
{
var left = '60' - now.minute;
$('#gh').html("<span class='gh_remind'>Grosshandel einstellen in " + left + " Minuten!</span>");
}
if (now.hour == "17" && now.minute >= "50")
{
var left = "60" - now.minute;
$('#gh').html("<span class='gh_remind'>Grosshandel einstellen in " + left + " Minuten!</span>");
}
else
{
$('#gh').html("");
}
}
if (now.day == "Samstag")
{
if (now.hour == "9" && now.minute >= "50")
{
var left = "60" - now.minute;
$('#gh').html("<span class='gh_remind'>Grosshandel einstellen in " + left + " Minuten!</span>");
}
if (now.hour == "12" && now.minute >= "50")
{
var left = "60" - now.minute;
$('#gh').html("<span class='gh_remind'>Grosshandel einstellen in " + left + " Minuten!</span>");
}
if (now.hour == "13" && now.minute >= "50")
{
var left = "60" - now.minute;
$('#gh').html("<span class='gh_remind'>Grosshandel einstellen in " + left + " Minuten!</span>");
}
else
{
$('#gh').html("");
}
}
}
Thanks for your help!

Consider this:
var a = 'a', b;
if (a == 'a') {
b = 'right';
}
if (a == 'c') {
b = 'wrong';
}
else {
b = 'FOOBAR!';
}
alert(b);
Even though you (probably) expect b to store 'right' value in the end of that if structure, it - surprise, surprise! - will contain FOOBAR instead. The reason is that if all your ifs are written like this, they're independent of each other. The first one will assign 'right' string to b variable - but the second one, going through else branch, will happily reassign it (to some foobar).
If you want to create a chain of ifs, use if - else if - else syntax instead:
var a = 'a', b;
if (a == 'a') {
b = 'right';
}
else if (a == 'c') {
b = 'wrong';
}
else {
b = 'FOOBAR!';
}
alert(b);
Now that will show you the right thing, right? )

Strings are not numbers. Do not use quotes around numbers unless you actually want it to be a string.
> console.log("1">"50")
false
> console.log("9">"50")
true

Related

Issues with using negative numbers in a prompt box

Very new to JavaScript, the first programming language I learned was Java. I am trying to make a simple website that displays the shortest distance between an infinite number of points using prompt boxes and a 2D array.
This code works as expected, however when one of the points has a negative number in it, nothing ever displays for an answer, throwing the error:
Uncaught TypeError: Cannot read property '0' of undefined
at run (index.html:54)
at HTMLButtonElement.onclick (index.html:63)
Google Chrome highlights the error at this line:
toRun = "Shortest distance is " + min + " with these points: (" + finalPoints[0][0] + ", " + finalPoints[1][0] + ") and (" + finalPoints[0][1] + ", " + finalPoints[1][1] + ").";
How can I get this program to work with negative numbers as well?
function run() {
var x, y;
var finalPoints = [];
var min = 0;
var toRun;
var temp;
var list = []; //using 2d array to store points
while (true) {
x = prompt("Enter an X-Value: ");
if (x == null || x == "") {
break;
}
y = prompt("Enter a Y-Value: ");
if (y == null || y == "") {
break;
}
list.push([x, y]);
}
if (list.length < 2) {
toRun = "Sorry, you didn't enter enough points for this program to run correctly. Please try again.";
} else if (list.length == 2) {
toRun = "Distance between points (" + list[0][0] + ", " + list[0][1] + ") and (" + list[1][0] + ", " + list[1][1] + ") is " + Math.sqrt(Math.pow((list[0][0] - list[1][0]), 2) + Math.pow((list[0][1] - list[1][1]), 2));
} else {
min = Math.sqrt(Math.pow((list[0][0] - list[1][0]), 2) + Math.pow((list[0][1] - list[1][1]), 2));
for (var i = 0; i < list.length; i++) {
for (var j = 0; j < list.length; j++) {
temp = Math.sqrt(Math.pow((list[i][0] - list[j][0]), 2) + Math.pow((list[i][1] - list[j][1]), 2));
if (temp < min && temp != 0) {
min = temp;
finalPoints.push([list[i][0], list[j][0]]);
finalPoints.push([list[i][1], list[j][1]]);
}
}
}
toRun = "Shortest distance is " + min + " with these points: (" + finalPoints[0][0] + ", " + finalPoints[1][0] + ") and (" + finalPoints[0][1] + ", " + finalPoints[1][1] + ").";
}
document.getElementById("output").innerHTML = toRun;
}
body {
background-color: #0d0d0d;
}
p,
button,
h3 {
color: #FFFFFF;
background-color: #0d0d0d;
}
button {
border: 1px solid #FFFFFF;
}
<h3>Continue entering points. When done, click cancel or don't enter anything.</h3>
<br>
<button onclick="run()" style="size:40%">Click me to start!</button>
<p id=output>(Output will display here).</p>

Read array of objects and output values by given conditions in JavaScript

Here is the problem:
Client wants to buy 2 same name PCs both color white or black with the total price less than 1600. Write a JavaScript program that would read given array var pcs and would find him the best offers.
var pcs = [
{ "model":"lenovo", "price":1234, "color":{"red":1,"green":2} },
{ "model":"hp", "price":800, "color":{"black":2,"yellow":0} },
{ "model":"toshiba", "price":256, "color":{"mėlyna":3,"green":1} },
{ "model":"dell", "price":697, "color":{"black":1,"white":2} },
{ "model":"acer", "price":620, "color":{"black":4,"white":2} },
{ "model":"apple", "price":2560, "color":{"white":3,"black":1} },
{ "model":"asus", "price":1001, "color":{"black":2,"yellow":3} }
],
PC,
Collors,
offer = "Offers: " + "\n";
for (var i = 0; i < pcs.length; i++) {
PC = pcs[i];
Collors = Object.keys(PC.color);
if ((((PC.price) * 2) <= 1600) && (PC.color.black >= 2 || PC.color.white >= 2)) {
for ( var j = 0; j < Collors.length; j++) {
if ((PC.color.black >= 2) && (PC.color.white >= 2)) {
offer += "\n" + "model: " + PC.model + "\n" + "price: " + (PC.price) * 2 + "\n"
+ "Collors: " + Collors[0] + " and " + Collors[1] + "\n";
}
else if (((PC.color.black >= 2) && (Collors[j] === "black"))) {
offer += "\n" + "model: " + PC.model + "\n" + "price: " + (PC.price) * 2 + "\n"
+ "Collors: " + Collors[j] + "\n";
}
else if (((PC.color.white >= 2) && (Collors[j] === "white"))) {
offer += "\n" + "model: " + PC.model + "\n" + "price: " + (PC.price) * 2 + "\n"
+ "Collors: " + Collors[j] + "\n";
}
}
}
}
console.log(offer);
Written code find the best offers, but could someone tell why acer in the output duplicates itself and how is possible to repair it?
Many thanks for all help,
You loop over Collors. For acer both black and white have >2. So the first rule that checks black and white matches once for black and once for white.
A solution is to not loop over Collors at all but check black and white separately directly:
var pcs = [
{ "model":"lenovo", "price":1234, "color":{"red":1,"green":2} },
{ "model":"hp", "price":800, "color":{"black":2,"yellow":0} },
{ "model":"toshiba", "price":256, "color":{"melyna":3,"green":1} },
{ "model":"dell", "price":697, "color":{"black":1,"white":2} },
{ "model":"acer", "price":620, "color":{"black":4,"white":2} },
{ "model":"apple", "price":2560, "color":{"white":3,"black":1} },
{ "model":"asus", "price":1001, "color":{"black":2,"yellow":3} }
],
PC,
Collors,
offer = [],
colors;
for (var i = 0; i < pcs.length; i++) {
colors = [];
PC = pcs[i];
if (PC.color.black >= 2) {
colors.push("black");
}
if (PC.color.white >= 2) {
colors.push("white");
}
if (PC.price * 2 <= 1600 && colors.length > 0) {
offer.push({
"model": PC.model,
"total price": PC.price * 2,
"color": colors
});
}
}
console.log(JSON.stringify(offer, undefined, "\t"));
Code to solve problem to get required output in console.
var pcs = [
{ "model":"lenovo", "price":1234, "color":{"red":1,"green":2} },
{ "model":"hp", "price":800, "color":{"black":2,"yellow":0} },
{ "model":"toshiba", "price":256, "color":{"mėlyna":3,"green":1} },
{ "model":"dell", "price":697, "color":{"black":1,"white":2} },
{ "model":"acer", "price":620, "color":{"black":4,"white":2} },
{ "model":"apple", "price":2560, "color":{"white":3,"black":1} },
{ "model":"asus", "price":1001, "color":{"black":2,"yellow":3} }
];
for (var i=0; i < pcs.length; i++) {
if((pcs[i].color.black >=2 || pcs[i].color.white >=2) && pcs[i].price *2 <=1600){
//console.log (pcs[i]);
var colors = Object.keys(pcs[i].color),
color = '';
for(var j = 0; j < colors.length; j++){
if ((pcs[i].color.black >= 2 && colors[j] === "black") ||
(pcs[i].color.white >= 2 && colors[j] === "white" )) {
if (color.length > 0) {
color += ' and ' + colors[j];
} else {
color = colors[j];
}
}
}
console.log('Model: ' + pcs[i].model + '\nPrice: ' + pcs[i].price*2 + '\nSpalvos: ' + color);
}
}

I'm new, and I cannot for the life of me find this syntax error

I do not understand why there is a syntax error in line 12, but there seems to be one.
g = 0
y = 0
c = 0
while(true) {
computer = random(3);
you = choose("Choose!", "Rock", "Paper", "Scissors");
if (computer == 1){
if (you == 2){
show("You win!");
g = g + 1;
y = y + 1;
if (g == 3) {
break;
show("Computer: " + c + "You: " + y);
}
} else if (you == 1) {
show("Draw");
g = g + 1;
if (g == 3) {
break;
show("Computer: " + c + "You: " + y;)
}
} else if (you == 3) {
show("Computer wins.");
g = g + 1;
c = c + 1;
if (g == 3) {
break;
show("Computer: " + c + "You: " + y;)
}
}
}
y;)} should be y);} in two places
another issue though, you have break; show(... in three places, the show I don't think will run after break
var g = 0,
y = 0,
c = 0;
while (true) {
computer = random(3);
you = choose("Choose!", "Rock", "Paper", "Scissors");
if (computer == 1) {
if (you == 2) {
show("You win!");
g = g + 1;
y = y + 1;
if (g == 3) {
break; // <=== break here?
show("Computer: " + c + "You: " + y);
}
} else if (you == 1) {
show("Draw");
g = g + 1;
if (g == 3) {
break; // <=== break here?
show("Computer: " + c + "You: " + y;) // <=== don't wink here ;)
}
} else if (you == 3) {
show("Computer wins.");
g = g + 1;
c = c + 1;
if (g == 3) {
break; // <==== break here?
show("Computer: " + c + "You: " + y;) // <=== don't wink here ;)
}
}
}
}
P.S. I use http://jsbeautifier.org/ to beautify my code before posting
It is easier to see if you actually clean up the code.
g = 0
y = 0
c = 0
while (true) {
computer = random(3);
you = choose("Choose!", "Rock", "Paper", "Scissors");
if (computer == 1) {
if (you == 2) {
show("You win!");
g = g + 1;
y = y + 1;
if (g == 3) {
break;
show("Computer: " + c + "You: " + y);
}
} else if (you == 1) {
show("Draw");
g = g + 1;
if (g == 3) {
break;
show("Computer: " + c + "You: " + y;)
}
} else if (you == 3) {
show("Computer wins.");
g = g + 1;
c = c + 1;
if (g == 3) {
break;
show("Computer: " + c + "You: " + y;)
}
}
}
You have several problems
show("Computer: " + c + "You: " + y;) should be show("Computer: " + c + "You: " + y);
Unclosed while loop.
Undefined functions such as random, choose and show.
breaking before actually running code. (Although won't cause any errors, it is most likely not intended)
You have a missing '}' at the end. Try beautify js to indent your code and use jsHint to spot the error.
Probably because you still have statements after "break;" which is unreachable.

If values are the same update code

http://liveweave.com/R9jW9x
I have 4 textbox's each representing a css padding location (ex. padding-top, padding-left, etc:)
I'm experimenting with value detections. What I'm trying to figure out is when padding top and bottom [A] are the same values (as well as left and right [B]) how to set the values to padding: A B;
If all are same to set value to padding: A;
If all are different set value to nothing/blank
and
If all are different, or A & B maybe same, but C and D maybe different then to set value to padding: A B C D;
The script works fine onload, but when the input values are changed my result is not finalizing.
Can anybody explain why this is?
$(document).ready(function() {
var top = $(".padding-top").val(),
bottom = $(".padding-bottom").val(),
left = $(".padding-left").val(),
right = $(".padding-right").val(),
result = $(".padding-final");
// Update padding code
var Finalize = function() {
if ((top === "") && (right === "") && (bottom === "") && (left === "")) {
// Check if all are empty
result.val("");
} else if ((top === right) && (bottom === left)) {
// If all are same
result.val("padding: " + top + "px;");
} else if ((top === bottom) && (left === right)) {
// Check if first two values are same
result.val("padding: " + top + "px " + left + "px;");
} else {
result.val("padding: " + top + "px " + right + "px " + bottom + "px " + left + "px;");
}
};
// Update padding code when sides change
$(window).on('load keyup change', function() {
Finalize();
});
});
I won't write the code for you. But, I will hopefully send you in the right direction:
First, you should check whether padding-top, padding-right, padding-bottom, and padding-left are equal to each other.
>> If they are equal, then you can set the middle one equal to any of the values (since they're equal).
>> If they are not equal, then you can check to see if top and bottom are equal to each other && left and right are equal to each other. If they are, then you can set the middle to the top/bottom number + " " + left/right number.
>> Else set the middle to top number, right number, bottom number, left number.
EDIT
Actually, I got to tinkering a bit with the idea and came up with this to help you a bit more. But, that's it. No more help from me!
var top = 2;
var bottom = 2;
var right = 5;
var left = 5;
top == bottom && right == left && top == left ? alert(top)
: top == bottom && right == left ? alert(top + " " + left)
: alert(top + " " + right + " " + bottom + " " + left);
JSFiddle
After you solve this, a more challenging problem would be to type numbers into the middle box and change the top/right/bottom/left paddings accordingly.
I would play with this
var a=$(".padding-top"), b=..., c=..., d=...;
var test=0,padding;
if (a) test += 1;
if (b&& b!=a) test += 2;
if (c && c!=a) test += 4;
if (d && d!=c && d!=a) test += 8;
if (test== 1) padding = a;
if (test== 2 || test == 3) padding = a + " " + b; // when a+b or just b, we need a and b
if (test>4 && test < 8) padding = a + " " + b + " " + c; // c, a+c or b+c
if (test > 8) padding = a + " " + b + " " + c " " + d;
Also you can do
$(".paddings").on('keyup change', function() {
Finalize();
});
and use IDs for padding-top, left, bottom, right
As stated cases in your question, i have made following code:
$(document).ready(function() {
var top = $(".padding-top").val(),
bottom = $(".padding-bottom").val(),
left = $(".padding-left").val(),
right = $(".padding-right").val(),
result = 'Padding: ';
// Applies new code value
function Finalize() {
if(top === bottom === left === right) {
//If all are same
result += top + ' ';
} else {
if ((top === bottom) && (left === right)) {
// Check if first two values are same
result += top + ' ' + left + ' ';
} else {
result += left + ' ' + right + ' ' + top + ' ' + bottom + ' ';
}
}
result += 'Px';
$('#middle-input').val(result);
}
Finalize();
$(".padding-inputs").on('keyup change', function() {
Finalize();
});
});

Javascript function - works in IE, not in chrome

To preface this, we are a small organization and this system was built by someone long ago. I am a total novice at javascript so I have trouble doing complicated things, but I will do my best to understand your answers. But unfortunately redoing everything from scratch is not really an option at this point.
We have a system of collecting data where clients use a login to verify a member ID, which the system then uses to pull records from an MS Access database to .ASP/html forms so clients can update their data. One of these pages has the following function that runs on form submit to check that data in fields a/b/c sum to the same total as d/e/f/g/h/i. It does this separately for each column displayed (each column is a record in the database, each a/b/c/d/e/f is a field in the record.)
The problem is with this section of the function:
for (var j=0; j<recCnt; j++) {
sumByType = milesSurf[j] + milesElev[j] + milesUnder[j];
sumByTrack = milesSingle[j] + milesDouble[j] + milesTriple[j] + milesQuad[j] + milesPent[j] + milesSex[j];
etc.
It should use javascript FOR to loop through each record and test to see if they sum to the same thing.
In Firefox and IE this is working properly; the fields sum properly into "sumByType" and "sumByTrack". You can see below I added a little alert to figure out what was going wrong:
alert(sumByType + " " + j + " " + recCnt + " " + milesSurf[j] + " " + milesElev[j] + " " + milesUnder[j]);
In Chrome, that alert tells me that the components of "sumByType" and "sumByTrack" (the various "milesXXXXX" variables) are undefined.
My question is: Why in Chrome is this not working properly, when in IE and FFox it is? Any ideas?
Full function code below:
function submitCheck(formy, recCnt) {
//2/10/03: added milesQuad
//---------------checks Q#4 that Line Mileage by type is the same as by track
var milesElev = new Array();
var milesSurf = new Array();
var milesUnder = new Array();
var milesSingle = new Array();
var milesDouble = new Array();
var milesTriple = new Array();
var milesQuad = new Array();
var milesPent = new Array();
var milesSex = new Array();
var sumByType = 0;
var milesLineTrack = new Array(); //this is for Q5 to compare it to mileage by trackage
var j = 0; var sumByTrack = 0; var liney; var yrOp;
//var str = "document.frm.milesElev" + j;
//alert(str.value);
for (var i in document.frm) {
if (i.substring(0, i.length - 1) == "milesElev") {
milesElev[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesSurf") {
milesSurf[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesUnder") {
milesUnder[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesSingle") {
milesSingle[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesDouble") {
milesDouble[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesTriple") {
milesTriple[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesQuad") {
milesQuad[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesPent") {
milesPent[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length - 1) == "milesSex") {
milesSex[parseInt(i.substring(i.length-1, i.length))] = parseFloat(document.frm[i].value); }
if (i.substring(0, i.length -1) == "milesLineTrack") {
milesLineTrack[parseInt(i.substring(i.length-1, i.length))] = document.frm[i].value; } //12/13/02 used to be parseFloat(document.frm[i].value)
if (i.substring(0,5)=="Lines") {
liney = document.frm[i].value;
if (parseInt(liney)<1 || isNaN(liney)) {
alert("Each mode must have at least 1 line. Please correct the value in question #2.");
document.frm[i].select(); return false; }}
if (i.substring(0,8)=="yearOpen") {
yrOp = document.frm[i].value;
if (parseInt(yrOp)<1825 || isNaN(yrOp)) {
alert("Please enter a year after 1825 for question #3");
document.frm[i].select(); return false; }
}
}
for (var j=0; j<recCnt; j++) {
sumByType = milesSurf[j] + milesElev[j] + milesUnder[j];
sumByTrack = milesSingle[j] + milesDouble[j] + milesTriple[j] + milesQuad[j] + milesPent[j] + milesSex[j];
//---------------to round sumByTrack and sumByType from a long decimal to a single decimal place, like frm 7.89999998 to 7.9.
sumByTrack = sumByTrack * 10;
if (sumByTrack != parseInt(sumByTrack)) {
if (sumByTrack - parseInt(sumByTrack) >= .5) {
//round up
sumByTrack = parseInt(sumByTrack) + 1; }
else { //truncate
sumByTrack = parseInt(sumByTrack); }}
sumByTrack = sumByTrack / 10;
sumByType = sumByType * 10;
if (sumByType != parseInt(sumByType)) {
if (sumByType - parseInt(sumByType) >= .5) {
//round up
sumByType = parseInt(sumByType) + 1; }
else { //truncate
sumByType = parseInt(sumByType); }}
sumByType = sumByType / 10;
//-------------end of rounding ---------------------------
if (sumByType != sumByTrack) {
if (isNaN(sumByType)) {
sumByType = "(sum of 4.a., b., and c.) "; }
else {
sumByType = "of " + sumByType; }
if (isNaN(sumByTrack)) {
sumByTrack = "(sum of 4.d., e., f., g., h., and i.) "; }
else {
sumByTrack = "of " + sumByTrack; }
alert("For #4, the 'End-to-End Mileage By Type' " + sumByType + " must equal the 'End-to-end Mileage By Trackage' " + sumByTrack + ".");
alert(sumByType + " " + j + " " + recCnt + " " + milesSurf[j] + " " + milesElev[j] + " " + milesUnder[j]);
return false;
}
//alert (milesLineTrack[j] + " " + milesSingle[j] + " " + 2*milesDouble[j] + " " + 3*milesTriple[j] + " " + 4*milesQuad[j] + " " + 5*milesPent[j] + " " + 6*milesSex[j]);
var singDoubTrip = (milesSingle[j] + 2*milesDouble[j] + 3*milesTriple[j] + 4*milesQuad[j] + 5*milesPent[j] + 6*milesSex[j])
//----------round singDoubTrip to one digit after the decimal point (like from 6.000000001 to 6.0)
singDoubTrip = singDoubTrip * 10;
if (singDoubTrip != parseInt(singDoubTrip)) {
if (singDoubTrip - parseInt(singDoubTrip) >= .5) {
//round up
singDoubTrip = parseInt(singDoubTrip) + 1; }
else { //truncate
singDoubTrip = parseInt(singDoubTrip); }}
singDoubTrip = singDoubTrip / 10;
//----------end round singDoubTrip-----------------------------------------
if (parseFloat(milesLineTrack[j]) != singDoubTrip) {
//var mlt = milesLineTrack[j];
//if isNaN(milesLineTrack[j]) { mlt =
alert("For column #" + (j+1) + ", the mainline passenger track mileage of " + milesLineTrack[j] + " must equal the single track plus 2 times the double track plus 3 times the triple track plus 4 times the quadruple track plus 5 times the quintuple track plus 6 times the sextuple track, which is " + singDoubTrip + ".");
return false;
}
}
//---------------------end of checking Q#4----------------
//return false;
}
I think for (var i in document.frm) is the problem. You should not enumerate a form element, there will be plenty of unexpected properties - see Why is using "for...in" with array iteration a bad idea?, which is especially true for array-like objects. I can't believe this works properly in FF :-)
Use this:
var ele = document.frm.elements; // or even better document.getElementById("frm")
for (var i=0; i<ele.length; i++) {
// use ele[i] to access the element,
// and ele[i].name instead of i where you need the name
}
Also, you should favour a loop over those gazillion of if-statements.

Categories