Learning JS from a book, the exercise question was this:
Modify the code of Question 1 to request the times table to be displayed from the user; the code
should continue to request and display times tables until the user enters ‐1. Additionally, do a check
to make sure that the user is entering a valid number; if the number is not valid, ask the user to
re‐enter it.
This is the proposed solution:
function writeTimesTable(timesTable, timesByStart, timesByEnd) {
for (; timesByStart <= timesByEnd; timesByStart++) {
document.write(timesTable + " * " + timesByStart + " = " +
timesByStart * timesTable + "<br />");
}
}
var timesTable;
while ((timesTable = prompt("Enter the times table", -1)) != -1) {
while (isNaN(timesTable) == true) {
timesTable = prompt(timesTable + " is not a " +
"valid number, please retry", -1);
}
if (timesTable == -1) {
break;
}
document.write("<br />The " + timesTable +
" times table<br />");
writeTimesTable(timesTable, 1, 12);
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 4: Question 2</title>
</head>
<body>
<script>
</script>
</body>
</html>
This is my code, which also runs with the same result, without != -1:
function writeTimesTable(timesTable, timesByStart, timesByEnd) {
for (; timesByStart <= timesByEnd; timesByStart++) {
document.write(timesTable + " * " + timesByStart + " = " +
timesByStart * timesTable + "<br />");
}
}
var timesTable;
while (timesTable = prompt("Enter the times table", -1)) {
while (isNaN(timesTable) == true) {
timesTable = prompt(timesTable + " is not a " +
"valid number, please retry", -1);
}
if (timesTable == -1) {
break;
}
document.write("<br />The " + timesTable +
" times table<br />");
writeTimesTable(timesTable, 1, 15);
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 4: Question 2</title>
</head>
<body>
<script>
</script>
</body>
</html>
Why do I need != -1 parameter in the first while statement, since my code runs perfectly fine? Why is it there, what is it for?
The check for -1 is almost but not quite superfluous. It catches the conditions 'user canceled prompt' and 'user entered an empty string' which evaluates to false. In your version, this terminates the loop but the requirement is to terminate at user input '-1'.
If a while loop doesn't return anything, it will return as -1 (or false). In the case of the original example, I assume that the != -1 condition is there for example purposes only so it makes more sense to a beginner.
Let's say you were only wanting to terminate the while loop when the user entered -2. To do that, you would need to specify the != -2 condition in the loop, but -1 would still terminate the loop.
You're telling the browser/compiler to keep executing the code in the while loop until the user enters -1. When timesTable gets the value "-1" - that is, when the user enters "-1" - the while loop stops running.
// timesTable gets what the user enters in the prompt
// while timesTable is not equal to -1, execute the code in brackets
while ((timesTable = prompt("Enter the times table", -1)) != -1) {
while (isNaN(timesTable) == true) {
timesTable = prompt(timesTable + " is not a " +
"valid number, please retry", -1);
Related
I'm fairly new to java script and I've encountered a problem while trying to make a else statement in visual studio 2017.
I've tried moving the curly brackets and the else around to see if maybe I've placed them into the wrong place and I've had no luck.
<script type="text/javascript">
var items = parseInt(prompt("enter number of items", ""));
var price = parseFloat(prompt("enter item price", ""));
var total = items * price
if (total >= 50); {
document.write("<h3>" + "cost... $" + total * .5 + "</h3>");
document.write("<h2>" + prompt("enter a name", "") + "</h2>");
}
else {
document.write("<h3>" + "cost... $" + total + "</h3>");
document.write("<h2>" + prompt("enter a name", "") + "</h2>");
}
</script>
Whenever I open it in a web page, nothing happens, But when i get rid of the else statement, the if statement would execute.
Delete the semicolon behind the if condition and then the code should work.
I am wanting to make an if statement that has an alert function.
However if I don't use the localstorage function the alert box will keep popping up but changes the marker.
If if do use the localstorage function the marker won't set the color.
Any ideas on what to do?
All help is appreciated.
var alerted = localStorage.getItem('alerted') || '';
if (alerted != 'yes') {
if (value.squawk == "7500" || value.squawk == "7600" ||value.squawk == "7700") {
console.log(value.hex + " is squawking " + value.squawk);
alert(value.hex + " is squawking " + value.squawk + ". This is usually an error in transponder transmission please DO NOT alert the local authorities");
markers[value.hex].setIcon(squawkerror(value));
}
} else
Just check for alerted around the alert and if not set, alert and set it. Next time, no alert will be set and no stored value will be changed.
var alerted = localStorage.getItem('alerted') || false;
if( value.squawk == 7500 || value.squawk == 7600 ||value.squawk == 7700 ){
console.log(value.hex + " is squawking " + value.squawk);
if( !alerted ){
alert(value.hex + " is squawking " + value.squawk + ". This is usually an error in transponder transmission please DO NOT alert the local authorities");
localStorage.setItem('alerted', true);
}
markers[value.hex].setIcon(squawkerror(value));
}
net mvc application and I am trying to do some validation when someone clicks a button. Here is the code.
function productVerify() {
var intQty = $("#txtQty").val();
var strItemName = $("#item_Name").val();
var strItemDescription = $("#item_Description").val();
var intItemID = $("#item_ID").val();
var intItemPrice = $("#item_Price").val();
var strImgUrl = $("item_ImgUrl").val();
var intQty = $("#txtQty").val();
if (intQty < 1) {
alert("You cannot put an item quantity of 0 in your cart");
return false;
}
else {
//post into cart
alert(strItemName + " " + strItemDescription + " " + intItemID + " " + intItemPrice + " " + strImgUrl + " " + intQty + " " + "I got this far.....! good job")
}
}
this works in jsfiddle but for some reason it does not fully work in my mvc application. it does work on the first if because if I put a 0 in my text box I get the first alert, but nothing happens on the else inside my mvc application. This one part seems so easy, but it is killing me any help would be appreciated.
make sure you using a number in your if statement
//if !num
if (parseInt(intQty) == NaN) {
alert("Please enter a number");
return false;
} else {
//if < 1
if (parseInt(intQty) < 1) {
alert("You cannot put an item quantity of 0 in your cart");
return false;
//if >= 1
} else {
//do something
}
}
This code is supposed prompt for two player names and generate a random number between 1 and 6 for each player. It is then supposed to compare those two numbers and provide the output of which player has the higher number or display tie if there is a tie. Sometimes this works and sometimes it does the opposite other times it says both numbers match when they don't.
Anyone have any ideas for me?
var playerOne = " "
var playerTwo = " "
var rollWinner = " "
var p1number = 0;
var p2number = 0;
var end = " "
main()
function main()
{
do {
getNames()
rollDice()
displayResults()
endProgram()
}
while (end == "yes")
}
function getNames()
{
playerOne = prompt("Please enter the name of Player One: ")
playerTwo = prompt("Please enter the name of Player Two: ")
}
function rollDice()
{
p1Number = Math.floor((Math.random()*6)+1)
p2Number = Math.floor((Math.random()*6)+1)
if (p1Number > p2Number)
{
return playerOne
}
else if (p1Number < p2Number)
{
return playerTwo
}
else
{
return "Sorry no winner, there was a tie"
}
}
function displayResults()
{
window.alert(playerOne + " rolled a " + p1Number)
window.alert(playerTwo + " rolled a " + p2Number)
window.alert("The winner is! " + rollDice())
}
function endProgram()
{
end = prompt("Do you want to play again? Enter yes or no")
if (end == "no")
window.alert("Thank you for playing");
else if (end == "yes")
return end;
}
window.alert("The winner is! " + rollDice())
This line calls rollDice again for a 2nd time. You display the results of the first call then you re-roll and display the return value of the 2nd call (which may be different).
// display p1Number and p2Number from first roll
window.alert(playerOne + " rolled a " + p1Number)
window.alert(playerTwo + " rolled a " + p2Number)
// recall rollDice
window.alert("The winner is! " + rollDice())
In displayResults(), you are showing the values of p1Number and p2Number before assigning values to them (since that happens within rollDice()).
So your program is working, but your diagnostic output is misleading you.
I'm coming here after a few hours of outstanding rage, anger, shock - perhaps just plain incredulity - at what's happened to me here.
I've attempted to create the simplest of functions in a lengthy script - get an element by Id, then change part of the class depending on a variable. Sounds easy right? Here's the relevant code:
{literal}
// check to see what kind of ban is this based on the ban_until and ban_at columns in table banlist from return data of /inc/classes/bans.class.php
var banduration = {/literal}{$ban.until - $ban.at}{literal};
if (banduration !== 1 || 0) {
var bantype = ((banduration < 0 || banduration > 3600) ? "ban" : "warning");
}
// replace all classnames with others in case this is a warning/ban, and END the script before it also changes modnames
if (bantype === "warning" || "ban") {
document.getElementbyId("modname_message_background").className = "common_background " + bantype + "_background";
document.getElementById("modname_message_bottomribbon").className = "common_bottomribbon " + bantype + "_bottomribbon";
document.getElementById("modname_message_letterbox").className = "common_letterbox " + bantype + "_letterbox";
document.getElementById("modname_message_modname").className = "common_modname " + bantype + "_modname";
document.getElementById("modname_message_servertime").className = "common_servertime " + bantype + "_servertime";
document.getElementById("modname_message_signature").className = "common_signature " + bantype + "_signature";
document.getElementById("modname_message_topribbon").className = "common_topribbon " + bantype + "_topribbon";
document.getElementById("modname_message_username").className = "common_username " + bantype + "_username";
}
This is fairly self-explanatory: This is in a Smarty template, and $ban.until is the unix time of a ban's end, and $ban.at is the unix time that it was applied, and so on and so on. But as I ran this script, which is designed to change the ban message depending on individual moderator ranks (later on but I digress) and the message type (message, warning, or ban). When I inserted this, only the first line was used. Agitated, I spent two hours reworking it multiple times in different ways to absolutely no avail. Furious with myself, I wrote this:
if (bantype == "warning" || "ban") {
var list = ["modname_message_background","modname_message_bottomribbon","modname_message_letterbox","modname_message_modname","modname_message_servertime","modname_message_signature","modname_message_topribbon","modname_message_username"];
var secondlist = ["background","bottomribbon","letterbox","modname","servertime","signature","topribbon","username"];
for (var i=0;i<list.length;i++) {
document.getElementById(list[i]).className = "common_" + secondlist[i] + " " + bantype + "_" + secondlist[i];
}
}
return;
This didn't work either. I was incredulous - defeated, I come here, pleading for the ludicrously simple mistake I had to have missed, because only something so simple can be such a nuisance.
I can confirm that variable banduration is working perfectly (using alert).
if (bantype === "warning" || "ban")
doesn't do what you think it does. It's equivalent to:
if ((bantype === "warning") || "ban")
which is always true, because "ban" is not false. It should be:
if (bantype === "warning" || bantype === "ban")
And:
if (banduration !== 1 || 0)
should be:
if (banduration !== 1 && banduration !== 0)