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);
Related
what is the best way to convert this into a while loop?
<html>
<head>
<script type="text/javascript">
<!--
function GetGrades() {
var grades = [];
var grade;
var sum = 0;
for(i=0; i<5; i++) {
grade = prompt("Enter Homework " + (i+1) + " grade: ");
grades.push(Number(grade));
}
for(i=0; i<5; i++) {
document.write("Homework " + (i+1) + " grade: " + grades[i] + "</br>");
sum = sum + grades[i];
}
var avg = sum/5.0;
document.write("</br>Grade: " + avg + "</br>");
}
//-->
</script>
</head>
<body onload="GetGrades()">
</body>
</html>
I have ignorantly tried to simply declare the variable i as sero and change the for to while.
while(i<5) {
grade = prompt("Enter Homework " + (i+1) + " grade: ");
grades.push(Number(grade));
i++;
}
while(i<5) {
document.write("Homework " + (i+1) + " grade: " + grades[i] + "</br>");
sum = sum + grades[i];
i++;
}
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"))" 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/
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>");
Below is my code which creates the textboxes dynamically in modal pop up each time when i click add button and removes the text boxes in that row each time when i click remove button which is working fine till here the problem is i have the javascript function which validates the month date and year in text box that if if we give any number greater than 12 it shows message that month should be less than 12 similarly for date also it will accept till 31 but if it is greater than 31 it shows error message and similarly year also but this is done for our asp text boxes how can i make this javascript function to work in modal pop where the textboxes are created dynamically
<script type="text/javascript">
function GetDynamicTextBox(value) {
if (value == "") {
FillDropdown()
return '<input name = "DynamicTextBox" value = "' + value + '" placeholder="MM/DD/YYYY"></input> <select name = "DynamicTextBox" >"' + Hours + '"</Select><b>:</b><select name = "DynamicTextBox">"' + Min + '"</Select>' +
' <input id="btnAdd123" type="button" value="Add" onclick="AddTextBox()" /><input type="button" value="Remove" onclick = "RemoveTextBox(this)" />'
//Min = "";
// Hours = "";
//
}
}
var HHEdit = "";
var MMEdit = "";
function GetDynamicTextBox1(value) {
values = value.split(' ');
one = values[0];
two = values[1];
values = two.split(':');
three = values[0];
Four = values[1];
HHEdit = three;
MMEdit = Four;
FillDropdown()
return '<input name = "DynamicTextBox" value = "' + one + '" placeholder="MM/DD/YYYY"></input> <select name = "DynamicTextBox" >"' + Hours + '"</Select><b>:</b><select name = "DynamicTextBox">"' + Min + '"</Select>' +
' <input id="btnAdd123" type="button" value="Add" onclick="AddTextBox()" /><input type="button" value="Remove" onclick = "RemoveTextBox(this)" />'
// $('.DynamicTextBox').val(one);
}
function AddTextBox() {
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
function AddTextBox1() {
var inputCount = document.getElementById('TextBoxContainer').getElementsByTagName('input').length;
if (inputCount == "0") {
var div = document.createElement('DIV');
div.innerHTML = GetDynamicTextBox("");
document.getElementById("TextBoxContainer").appendChild(div);
}
}
function RemoveTextBox(div) {
document.getElementById("TextBoxContainer").removeChild(div.parentNode);
}
function RecreateDynamicTextboxes() {
var values = eval('<%=Values%>');
if (values != null) {
var html = "";
for (var i = 0; i < values.length; i++) {
html += "<div>" + GetDynamicTextBox1(values[i]) + "</div>";
}
document.getElementById("TextBoxContainer").innerHTML = html;
}
}
var Hours = "";
var Min = "";
function FillDropdown() {
for (var i = 0; i < 24; i++) {
if (i >= 0 && i <= 9) {
if (HHEdit != "" && HHEdit == i) {
Hours += '<option value="' + i + '" selected="selected">' + " 0" + i + " " + '</option>'
}
else {
Hours += '<option value="' + i + '">' + " 0" + i + " " + '</option>';
}
}
else {
if (HHEdit != "" && HHEdit == i) {
Hours += '<option value="' + i + '" selected="selected">' + " " + i + " " + '</option>';
}
else {
Hours += '<option value="' + i + '">' + " " + i + " " + '</option>';
}
}
}
for (var i = 0; i < 60; i++) {
if (i >= 0 && i <= 9) {
if (MMEdit != "" && MMEdit == i) {
Min += '<option value="' + i + '" selected="selected">' + " 0" + i + " " + '</option>';
}
else {
Min += '<option value="' + i + '">' + " 0" + i + " " + '</option>';
}
}
else {
if (MMEdit != "" && MMEdit == i) {
Min += '<option value="' + i + '" selected="selected">' + " " + i + " " + '</option>';
}
else {
Min += '<option value="' + i + '">' + " " + i + " " + '</option>';
}
}
}
//$('#Item').append(option);
}
window.onload = RecreateDynamicTextboxes;
</script>
Code for date month year validation using javascript
var fdate = document.getElementById('<%=txtFromDate.ClientID%>').value;
var tdate = document.getElementById('<%=txtToDate.ClientID%>').value;
var fromdate = fdate.split('/');
var fmonth = fromdate[0];
var fdate = fromdate[1];
var fyear = fromdate[2];
if (fmonth > 12) {
message += "From Month Should Be Less Than 12." + "\n";
}
if (fdate > 31) {
message += "From Date Cannot Be Greater Than 31." + "\n";
}
if (fyear < 2000 || fyear > 2030) {
message += "From Year Should Be In Between 2000 to 2030." + "\n";
}
var todate = tdate.split('/');
var tmonth = todate[0];
var tdate = todate[1];
var tyear = todate[2];
if (tmonth > 12) {
message += "To Month Should Be Less Than 12." + "\n";
}
if (tdate > 31) {
message += "To Date Cannot Be Greater Than 31." + "\n";
}
if (tyear < 2000 || tyear > 2030) {
message += "To Year Should Be In Between 2000 to 2030."+"\n";
}
if (message != "") {
alert(message);
return false;
}
From Date: <asp:TextBox ID="txtFromDate" Width="113px" runat="server" placeholder="mm/dd/yyyy" onkeypress="return IsValidData(event);" ondrop="return false;"
onpaste="return false;" onkeyup="this.value=this.value.replace(/^(\d\d)(\d)$/g,'$1/$2').replace(/^(\d\d\/\d\d)(\d+)$/g,'$1/$2').replace(/[^\d\/]/g,'')"></asp:TextBox> <span id="error" style="color: Red; display: none">* Invalid Character</span>
To Date: <asp:TextBox ID="txtToDate" Width="113px" runat="server" placeholder="mm/dd/yyyy" onkeypress="return IsValidData(event);" ondrop="return false;"
onpaste="return false;" onkeyup="this.value=this.value.replace(/^(\d\d)(\d)$/g,'$1/$2').replace(/^(\d\d\/\d\d)(\d+)$/g,'$1/$2').replace(/[^\d\/]/g,'')"></asp:TextBox><span id="Span1" style="color: Red; display: none">* Invalid Character</span>
I don't see that you've actually defined your IsValidData function. I'm assuming that you've done that somewhere...
You can pass this to your IsValidData function as a parameter to work with the element that triggered the event in your function..
Also you should try moving away from inline functions to event listeners. This stack post (JavaScript click event listener on class) talks about applying an event listener to a class of DOM elements.
If you are using jQuery, since you included this tag, then I'd encourage you to look into the jQuery .on() function to add event handlers. It'll make everything much easier (http://api.jquery.com/on/)
If you do not know what a javascript event listener is, then start here (https://www.w3schools.com/js/js_htmldom_eventlistener.asp)
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);
}
}