Prompt() method in Javascript - javascript

I'm a beginner to Javascript and I have a basic question about how to use the prompt method. None of the code seems to process below. Is there some sort of hidden rule about using multiple prompt boxes or does my code just have a syntax error? Any help would be much appreciated. Thanks in advance.
<html>
<head>
<title> Two Numbers </title>
<script type="text/javascript">
var first = prompt("Enter first number:");
var second = prompt("Enter second number:");
var sum = (first-0) + (second-0);
var diff = first - second;
var divide = first/second;
var multi = first*second;
document.write(first + " + " + second " = " + sum + "<br />");
document.write(first + " + " + second " = " + diff + "<br />");
document.write(first + " + " + second " = " + divide + "<br />");
document.write(first + " + " + second " = " + multi + "<br />");
</script>
</head>
<body>
</body>
</html>

You're missing a +.
//change this
console.log(first + " + " + second " = " + sum + "<br />");
// to this
console.log(first + " + " + second + " = " + sum + "<br />");
In the future, please use the console for debugging. There is a great article on everything you can do with the console here > https://developer.chrome.com/devtools/docs/javascript-debugging

Corrected the syntax error and corrected the operators in the write() function:
<html>
<head>
<title> Two Numbers </title>
<script type="text/javascript">
var first = prompt("Enter first number:");
var second = prompt("Enter second number:");
var sum = (first-0) + (second-0);
var diff = first - second;
var divide = first/second;
var multi = first*second;
document.write(first + " + " + second + " = " + sum + "<br />");
document.write(first + " - " + second + " = " + diff + "<br />");
document.write(first + " / " + second + " = " + divide + "<br />");
document.write(first + " * " + second + " = " + multi + "<br />");
</script>
</head>
<body>
</body>
</html>
use the console to check for errors, as said by James G

var isValid = true;
var first = prompt("Enter first number:");
if (!Number(first)) {
alert("Please enter numeric value only.");
isValid = false;
}
if (isValid) {
var second = prompt("Enter second number:");
if (!Number(second)) {
alert("Please enter numeric value only.");
isValid = false;
}
if (isValid) {
var sum = first + second;
var diff = first - second;
var divide = first / second;
var multi = first * second;
console.log(first + " + " + second + " = " + sum);
console.log(first + " - " + second + " = " + diff)
console.log(first + " / " + second + " = " + divide);
console.log(first + " * " + second + " = " + multi);
}
}

Related

Toggle function problem, What am I doing wrong?

I've created a comment system that posts comments in an ordered list. My requirememnts were to add hide/show toggle function to each comment.
Currently, the toggle function only works on the first comment (even when you try to click on 2nd, 3rd, etc.)
I've tried to use querySelectAll, but it didn't work for me. What am I doing wrong?
<div class="textbox">
<h3>Leave comments</h3>
<label for=msg>Name</label><br>
<input type=text id=fname> <br>
<label for=msg>Content</label><br>
<textarea id=msg> </textarea>
<br>
<input type=button onclick="postcomments()" value="Send" />
<input type="reset" value="Reset" />
<ol id="showcomments" style="max-width:200px; font-size:12px; padding-left:10px;">
</ol>
</div>
<script>
var ans = [];
function postcomments() {
var fname = document.getElementById("fname").value;
var msg = document.getElementById("msg").value;
var lastpos = ans.length;
var current = new Date();
console.log(current);
var time = current.getHours() + ":" + (current.getMinutes() < 10 ? '0' : '') + current.getMinutes();
var date = current.getDate() + "." + (current.getMonth() + 1) + "." + current.getFullYear();
var i = 0;
ans[lastpos] = '<img src="Media/minusicon.png" alt="minusicon" onclick="toggle(document.getElementById("txt&quot))" style="width:8%;" id="plusminusicon">' + " " + "Sent By" + " " + '' + fname + '' + " " + " In" + " " + date + " " + "At" + " " + time + '<br>' + '<span id="txt" class="toggle_panel">' + msg + '</span>' + '<br>' + '-------------------------------';
var ol = document.getElementById("showcomments");
ol.innerHTML = "";
for (var i = 0; i < ans.length; i++) {
ol.innerHTML += "<li id=" + (i + 1) + ">" + ans[i] + "</li>";
}
}
function toggle(x) {
if (x.style.display === "none") {
x.style.display = "block";
document.getElementById("plusminusicon").src = "Media/minusicon.png";
} else {
x.style.display = "none";
document.getElementById("plusminusicon").src = "Media/plusicon.png";
}
}
</script>
You have always the same id for all "txt" span, so the browser change always the first.
If you don't want change much of your code the simpliest solution is add the lastpost variable to the span id and to the parameter of toggle function.
Here the changes to do:
ans[lastpos] = '<img src="Media/minusicon.png" alt="minusicon" onclick="toggle(' + lastpos + ')" style="width:8%;" id="plusminusicon' + lastpos + '">' + " " + "Sent By" + " " + '' + fname + '' + " " + " In" + " " + date + " " + "At" + " " + time + '<br>' + '<span id="txt' + lastpos + '" class="toggle_panel">' + msg + '</span>' + '<br>' + '-------------------------------';
function toggle(x) {
let comment = document.getElementById("txt" + x);
let icon = document.getElementById("plusminusicon" + x);
if (comment.style.display === "none") {
comment.style.display = "block";
icon.src = "Media/minusicon.png";
} else {
comment.style.display = "none";
icon.src = "Media/plusicon.png";
}
}
To bind click listeners to dynamically added elements, you can use event delegation.
document.addEventListener('click', function(e) {
if (e.target && e.target.classList.contains('comment')) {
// do something
}
})
jQuery makes it even easier.
$(document).on('click','.comment',function(){ //do something })
And here's a jsfiddle link to the complete code example. https://jsfiddle.net/ep2bnu0g/

How to get JSON result in grid/tabular format while calling an API?

I'm using railway API in my website and want the Train data in grid format. Please help me with the same.
I want all the variables (Train name, Train number, Departure Time, Arrival Time, Travel Time, Availability Status) in a table format. I'm calling two APIs to get the final result. How can I achieve this using AngularJs?
function between(trainData) {
var total = trainData.TotalTrains;
for (i = 0; i < total; i++) {
var source = trainData.Trains[i].Source;
var destination = trainData.Trains[i].Destination;
var name = trainData.Trains[i].TrainName;
var number = trainData.Trains[i].TrainNo;
var ttime = trainData.Trains[i].TravelTime;
var deptime = trainData.Trains[i].DepartureTime;
var arrtime = trainData.Trains[i].ArrivalTime;
$('.' + className + '').append("<br/>" + name + "(" + number + ")" + " " + ttime + " " + deptime + " " + arrtime + "<br/>");
}
}
}
you can append with the in the end like
$('.' + className + '').append("<table><tr><th>name</th><th>number </th><th>ttime </th><th>deptime </th><th>arrtime </th><th>classcode </th><th>status </th><th>jdate </th></tr><tr><td>" + name + "</td><td>" + number + "</td><td>" + ttime + "</td><td>" + deptime + " </td><td>" + arrtime + " </td><td>" + classcode + "</td><td>" + status + "</td><td>" + jdate + "</td></tr></table>");

Why does my code display "player not found"?

So I have this command that's supposed to display a player's stats if it's found and says player not found otherwise. After I search a player and go to the previous screen, I get "player not found". I thought it was because my loop continues running after the player is found and my boolean becomes false, so I added a break statement. Won't work
function Search(Table, Stat1, Stat2, Stat3, Stat4, Stat5) {
onEvent("Search2.btn", "click", function() {
readRecords(Table, {}, function(records) {
var SearchPlayer = getText("text_input1");
var found = false;
for (var i = 0; i < records.length; i++) {
if ((records[i]).Player == SearchPlayer) {
setScreen("DisplaySearch");
setText("label3", records[i].Player + " Stats" + "\n" + records[i][Stat1] + " " + Stat1 + "\n" + records[i][Stat2] + " " + Stat2 + "\n" + records[i][Stat3] + " " + Stat3 + "\n" + records[i][Stat4] + " " + Stat4 + "\n" + records[i][Stat5] + " " + Stat5 + "\n");
setText("text_input1", "");
setText("label5", "");
found = true;
break;
} else if ((found == false)) {
setText("label5", "Player Not Found");
}
}
});
});

Why is the output being overwritten for this javascript

Expanded a previous question and it is working fine with the exception to the daily output. As the user enters each week/daily intake of supplement packs it should display to screen until the number of days entered is met. If a user input 2 weeks and 3 days (number of days packs were taken each week) the output should look like:
Week 1
Number of packs taken on Day 1 = 2
Number of packs taken on Day 2 = 1
Number of packs taken on Day 3 = 3
Week 2
Number of packs taken on Day 1 = 1 etc....
My code keeps writing over Week 1. I'm sure this is something simple that I overlooked. Maybe a variable to hold each weeks input? My code thus far...thanks for the help.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Daily Supplement Intake Log</title>
<script>
function getSup() {
var numWeeks = parseInt(document.getElementById("week").value);
var daysPerWeek = parseInt(document.getElementById("day").value);
var sum = 0;
var i = 0;
var total = 0;
while(i < numWeeks) {
var d = 0;
var grandTotal = 0;
var maxPacks = 0;
var highDay = 0;
while(d < daysPerWeek){
var packsTaken = prompt("Enter the number of packs taken on week " + (i + 1) + " and day "+ (d + 1), "");
total = parseInt(packsTaken);
document.getElementById("output2").innerHTML+="Number of packs for day " + (d + 1) + " = " + total + "<br />";
if(packsTaken > maxPacks){
maxPacks = packsTaken;
highDay = d;
}
sum += total;
d++;
}
grandTotal += sum;
i++;
document.getElementById("output1").innerHTML="Week " + i + "<br />";
document.getElementById("output3").innerHTML="Week " + i + "
subtotal is " + sum + " supplement packs." + "<br>"
+ "Week " + i + " largest day is " + maxPacks + " packs, on day " + d + "<br>";
}
document.getElementById("output4").innerHTML="The total for these weeks
is " + grandTotal + " supplement packs." + "<br>";
}
</script>
<body>
<header><h1>Daily Supplement Packet Log</h1></header><br>
<section>
<div class="align">
<label>Number of weeks:</label>
<input type="text" name="textbox" id="week" value=""><br>
<label>Number of days per week:</label>
<input type="text" name="textbox" id="day" value=""><br></div>
<div id="button">
<button type="button" id="log" onclick="getSup()">Enter number of packs
taken each day</button></div>
</section>
<div id="output1"></div>
<div id="output2"></div>
<div id="output3"></div>
<div id="output4"></div>
</body>
</html>
Using document.createElement method to dynamically create and order output divs. JSFiddle demo.
First replace your <div id="output1"></div>, ...2, ...3, and ...4 divs with:
<div id="outputs"></div>
<div id="total"></div>
...and then swap your getSup function with this:
function getSup() {
var numWeeks = parseInt(document.getElementById("week").value);
var daysPerWeek = parseInt(document.getElementById("day").value);
var sum = 0;
var i = 0;
var total = 0;
var d = 0;
var grandTotal = 0;
var maxPacks = 0;
var highDay = 0;
var packsTaken;
var tempDiv, weekListText
var outputs = document.getElementById("outputs");
while(i < numWeeks) {
d = 0;
grandTotal = 0;
maxPacks = 0;
highDay = 0;
weekListText = '';
while(d < daysPerWeek){
packsTaken = prompt("Enter the number of packs taken on week " + (i + 1) + " and day "+ (d + 1), "");
total = parseInt(packsTaken);
//document.getElementById("output2").innerHTML+="Number of packs for day " + (d + 1) + " = " + total + "<br />";
weekListText += "Number of packs for day " + (d + 1) + " = " + total + "<br />";
if(packsTaken > maxPacks){
maxPacks = packsTaken;
highDay = d;
}
sum += total;
d++;
}
grandTotal += sum;
i++;
//document.getElementById("output1").innerHTML="Week " + i + "<br />";
tempDiv = document.createElement('div');
tempDiv.innerHTML = "Week " + i;
outputs.appendChild(tempDiv);
// formerly known as output2
tempDiv = document.createElement('div');
tempDiv.innerHTML = weekListText;
outputs.appendChild(tempDiv);
//document.getElementById("output3").innerHTML="Week " + i + "subtotal is " + sum + " supplement packs." + "<br>" + "Week " + i + " largest day is " + maxPacks + " packs, on day " + d + "<br>";
tempDiv = document.createElement('div');
tempDiv.innerHTML = "Week " + i + "subtotal is " + sum + " supplement packs." + "<br>" + "Week " + i + " largest day is " + maxPacks + " packs, on day " + d + "<br>";
outputs.appendChild(tempDiv);
}
document.getElementById("total").innerHTML="The total for these weeks is " + grandTotal + " supplement packs." + "<br>";
}
This is mostly the same as the original, but I've rem'ed out the old innerHTML assignments and moved the vars up to the top of the function to reflect actual variable scope.
You overwrite the html, you do not append to it like you do in the loop.
document.getElementById("output1").innerHTML="Week " + i + "<br />";
document.getElementById("output3").innerHTML="Week " + i + "
should be
document.getElementById("output1").innerHTML += "Week " + i + "<br />";
document.getElementById("output3").innerHTML += "Week " + i + ";
but that is not going to make the output you want since they are the same sections. You really should be appending new elements to the page.
var header = document.createElement("h2");
header.innerHTML = "Week " + i;
document.getElementById("output1").appendChild(header);
var div = document.createElement("div");
div.innerHTML = "new content";
document.getElementById("output1").appendChild(div);

Javascript openWindow with my Chart

I working on a project for my class and I currently after the users takes a quiz, numbers are generated and it creates a graph. I need to get this graph on a new window. HOW DO I MOVE THIS WHOLE CHART to the window.open tab.
Here is my code:
openwindow = window.open("", "Best Fits","width=600,height=700,")
openwindow.document.write("Our top recommendation: "+ vare[0][0]+": " + vare[0][2] + "<br /> <br />" + "Our second recommendation: "+ vare[1][0]+": " + vare[1][2] + "<br /> <br />" + "Our third recommendation: "+ vare[2][0] + ": " + vare[2][2]);
//alert(Math.min(vare[0],vare[1],vare[2],vare[3],vare[4]))
alert(vare[0][0] +": " + vare[0][1] + " " + vare[1][0] +": " + vare[1][1] + " " + vare[2][0] +": " + vare[2][1] + " " + vare[3][0] +": " + vare[3][1] + " " + vare [4][0] +": " + vare[4][1] + " " + results[0] + " " + results[1] + " " + results[2] + " " + results[3])
alert(vare[0][0]+": " + vare[0][1]);
myData = new Array([vare[0][0],vare[0][1]],[vare[1][0],vare[1][1]],[vare[2][0],vare[2][1]])
var colors = ['#FACC00', '#FB9900', '#FB6600'];
var myChart = new JSChart('graph', 'pie');
myChart.setDataArray(myData);
myChart.colorizePie(colors);
myChart.setTitle('Hotel');
myChart.setTitleColor('#857D7D');
myChart.setPieUnitsColor('#9B9B9B');
myChart.setPieValuesColor('#6A0000');
myChart.draw();
});
});
}
I need to open MyChart with the saved variables on to a new tab.
THANKS!
Open them with a blank URL and openwindow.document.write their content into them, like:
var openwindow = window.open("", "Best Fits","width=600,height=700,")
var chrt = "";
myData = new Array([vare[0][0],vare[0][1]],[vare[1][0],vare[1][1]],[vare[2][0],vare[2][1]])
var colors = ['#FACC00', '#FB9900', '#FB6600'];
var myChart = new JSChart('graph', 'pie');
chrt += myChart.setDataArray(myData);
chrt += myChart.colorizePie(colors);
chrt += myChart.setTitle('Hotel');
chrt += myChart.setTitleColor('#857D7D');
chrt += myChart.setPieUnitsColor('#9B9B9B');
chrt += myChart.setPieValuesColor('#6A0000');
chrt += myChart.draw();
openwindow.document.write(chrt);

Categories