how to declare div and id/class in java script - javascript

I have the index.html file in that form fields are there form action is confirm.html. In confirm.html some data, I displayed using js. But showing the only table I decided to I use menus in that so more attractive for users. Whenever I'm trying to declare div(<h1>data</h1>) in confirm.html it won't be showing any data. so I decided to declare using js.
Top of the headers i have to show those menus:
document.write("<div class="Menu">");
document.write("<div class="leftmenu">");
document.write("<h4>Fegli</h4>");
document.write("<div class="Menu">");
doucment.write("<ul>");
document.write("<li>Home</li>");
document.write("</ul>");
document.write("</div>");
document.write("</div>");
document.write("</div>");
Confirm.html: code
<html>
<head>
<script type="text/javascript" src="calculate.js">
</script>
</head>
<body onload="init();">
<div id="Menu">
it wont showing on web page
</div>
</body>
</html>
Calculate.js code
// Called on body's `onload` event
var cumulative=0;
function init() {
var salary = parseInt(localStorage.getItem("salary"));
var percent = parseFloat(localStorage.getItem("percent"));
var age = parseInt(localStorage.getItem("age"));
var rAge = parseInt(localStorage.getItem("rAge"));
var sel = localStorage.getItem("sel");
var roundedSalary = parseInt(Math.ceil((salary + 2000) / 1000) * 1000); //Doing Rounding for basic column Display
var basic;
var factor = 0;
var biWeekly = 0, monthly = 0,annual = 0;
//Displaying Headers
document.write("<head>");
document.write("<link rel=\"stylesheet\" type=\"text/css\" href=\"confirm.css\">");
document.write("<title>Result</title>");
document.write("</head>");
document.write("<body>");
/* document.write("<center>")
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1; //January is 0!
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}
today = mm + '/' + dd + '/' + yyyy;
document.write("<h1>" + "FEGLI CALCULATIONS ON" + " " + today + "</h1>");
document.write("</center>")
*/
document.write("<table><tr><th> Age </th><th> Annual-Salary </th><th> BiWeekly-Premium </th><th> Monthly-Premium </th><th> Annual-Premium </th><th> Cumulative-Premium </th><th>Basic </th><th> Total </th></tr>");
basic = parseInt(roundedSalary * calculateFactor(age));
//document.write("roundedSalary"+roundedSalary+"calculateFactor"+calculateFactor(age));
premium = calculateBiweekly(salary, basic, age, rAge);
biWeekly = premium[0];
monthly = premium[1];
annual = premium[2];
cumulative = premium[3];
document.write("<tr><td>" + age + "/" + (age + 1) + "</td><td>" + "$" + salary.toFixed(2) + "</td><td>" + "$" + biWeekly.toFixed(2) + "</td><td>" + "$" + monthly.toFixed(2) + "</td><td>" + "$" + annual.toFixed(2) + "</td><td>" + "$" + cumulative.toFixed(2) + "</td><td>" + "$" + basic + "</td><td>-</td></tr>");
salary = parseFloat(salary);
for (var i = age + 1; i < 101; i++) {
document.write("<tr>");
document.write("<td>" + i + "/" + (i + 1) + "</td>");
if (i < rAge) {
salary = salary + (salary * percent);
roundedSalary = parseInt(Math.ceil((salary + 2000) / 1000) * 1000);
// document.write("age"+i+"roundedSalary"+roundedSalary+"<br>");
document.write("<td>" + "$" + salary.toFixed(2) + "</td>");
} else {
salary = 0;
document.write("<td>-</td>");
}
basic = parseInt(roundedSalary * calculateFactor(i));
premium = calculateBiweekly(salary, basic, i);
biWeekly = premium[0];
monthly = premium[1];
annual = premium[2];
cumulative = premium[3];
document.write("<td>" + "$" + biWeekly.toFixed(2) + "</td>");
document.write("<td>" + "$" + monthly.toFixed(2) + "</td>");
document.write("<td>" + "$" + annual.toFixed(2) + "</td>");
document.write("<td>" + "$" + cumulative.toFixed(2) + "</td>");
document.write("<td>" + "$" + basic + "</td>");
document.write("<td>-</td>");
document.write("</tr>");
}
document.write("</table>");
document.write("</body>")
}
function calculateFactor(age) {
var factor = 0;
if (age > 35 && age < 45) {
switch (age) {
case 36:
factor = 1.9;
break;
case 37:
factor = 1.8;
break;
case 38:
factor = 1.7;
break;
case 39:
factor = 1.6;
break;
case 40:
factor = 1.5;
break;
case 41:
factor = 1.4;
break;
case 42:
factor = 1.3;
break;
case 43:
factor = 1.2;
break;
case 44:
factor = 1.1;
break;
}
} else if (age <= 35) {
factor = 2;
} else if (age >= 45) {
factor = 1;
}
return factor;
}
function calculateBiweekly(salary, basic, age) {
var biWeekly = 0;
if (salary > 0) {
biWeekly = ((basic / calculateFactor(age)) * 0.15) / 1000;
monthly = ((basic / calculateFactor(age)) * 0.325) / 1000;
} else if (salary == 0 && age <= 65) {
biWeekly = ((basic / calculateFactor(age)) * (2.455 / 2.166)) / 1000;
monthly = ((basic / calculateFactor(age)) * (2.455)) / 1000;
} else if (salary == 0 && age > 65) {
//document.write("age"+age+"salary"+salary+"<br>");
biWeekly = ((basic / calculateFactor(age)) * (2.13 / 2.166)) / 1000;
monthly = ((basic / calculateFactor(age)) * (2.13)) / 1000;
}
annual = 12 * monthly;
cumulative = cumulative+annual;
//document.write("cumulative"+cumulative+"<br>");
return [biWeekly, monthly, annual, cumulative];
}// Called on body's `onload` event

I don't recommend document.write() to create element in DOM.
You need to use document.createElement() function to create new element using javascript.
function addMenu() {
var html = '<div class="Menu">';
html += '<div class="leftmenu">';
html += '<h4>Fegli</h4>';
html += '<div class="Menu">';
html += '<ul><li>Home</li></ul>';
html += '</div>';
html += '</div>';
html += '</div>';
document.getElementById("Menu").innerHTML = html;
}
addMenu();
<div id="Menu"></div>
In your code you applied table using document.write(), you can also create table tag using document.createElement() function. check below examples:
Example 1 :
function addTable() {
var c, r, t;
t = document.createElement('table');
t.border=1;
r = t.insertRow(0);//create row
c = r.insertCell(0);///create cell
c.innerHTML = "Apple";
c = r.insertCell(1);///create second cell
c.innerHTML = "Orange";
document.getElementById("mainContainer").appendChild(t);
}
addTable();
<div id="mainContainer"></div>
Example 2 :
function addTable() {
var html = "<table border='1'><tr><td>Apple</td><td>Orange</td></tr></table>";
document.getElementById("mainContainer").innerHTML = html;
}
addTable();
<div id="mainContainer"></div>
Both example will give same result.

Related

How can I make a symmetric histogram like this?

I'd like to write a JavaScript program that displays a symmetric histogram like this image:
The program should ask the user to enter the number of bars to print and the character to use to draw the bars. The count of characters in the bar needs to be displayed on the right-side of each bar.
The example showed is when I entered # as the character and 13 as the number.
Here's my code:
var symbol = prompt("Enter the symbol");
var number = prompt("Enter the number");
var currentNum = 1;
let text = "";
let symbolNum = symbol;
while (currentNum <= number) {
text += "<br>" + symbolNum + " " + currentNum;
symbolNum += symbol;
currentNum++;
}
document.write(text + "<br>");
And at last, I only can output the following:
I'd like to know what I can do in order to reverse the loop?
Try this
function SymmetricHistogram(){
const size = 10;
let numberX = 0;
let numberY = 0;
for(let i = size; i>=-size; i--) {
for(let j=size; j>=Math.abs(i); j--){
process.stdout.write("#");
}
numberX <=size ? console.log(numberX++) : console.log(--numberY);
}
}
SymmetricHistogram();
Or try the below
https://onecompiler.com/javascript/3x58bqr3h
Two different way for the same result. Not realy clean, but work.
var symbol = prompt("Enter the symbol");
var number = prompt("Enter the number");
var currentNum = 1;
let textTOP = "";
let textBOTTOM = "";
let symbolNum = symbol;
while (currentNum <= number) {
textTOP += "<br>" + symbolNum + " " + currentNum;
if (currentNum < number)
textBOTTOM = "<br>" + symbolNum + " " + currentNum + textBOTTOM;
symbolNum += symbol;
currentNum++;
}
document.write(textTOP + textBOTTOM + "<br>");
var symbol = '#';
var number = 13;
var currentNum = 1;
let text = "";
while (currentNum < number * 2) {
if (currentNum <= number) {
let num = currentNum;
text += "<br>" + symbol.repeat(num) + " " + num;
} else {
let num = Math.abs(number * 2 - currentNum);
text += "<br>" + symbol.repeat(num) + " " + num;
}
currentNum++;
}
document.write(text + "<br>");

JavaScript to display recent birthday wishes using arrays

With below code I'm trying to write the code to display recent (from date of b'day to 15 days) b'day wishes. At present nothing is displayed. I'm new to JavaScript, so need your help.
var dates = ["02/09/2009", "12/10/2010", "02/01/2001"];
var names = ["Mac", "Jac", "Tom"];
var today = new Date();
alert(today.getMonth()+1);
//alert(today.getDay());
//alert(typeof(day));
for(var i = 0; i < dates.length; i++) {
if (dates[i].split('/')[0] = today.getDay() && dates[i].split('/')[1] = today.getMonth()+1 && dates[i].split('/')[0] <= today.getDay()+15)
{
document.getElementById("demo").innerHTML = "Wish You Happy Birthday, " + names[dates.indexOf(dates[i])] + "(" + dates[i] + ")";
}
else{
document.getElementById("demo").innerHTML = "No matches";
}
}
<p id="demo"></p>
At last, with 3rd approach I could make it work, that you all for your help!
function parseDate(str) {
var mdy = str.split('/');
return new Date(mdy[2], mdy[0]-1, mdy[1]);
}
// Take the difference between the dates and divide by milliseconds per day.
// Round to nearest whole number to deal with DST.
function datediff(first, second) {
return Math.round((second-first)/(1000*60*60*24));
}
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var y = today.getFullYear();
var dates = ["10/16/" + y, "09/20/" + y, "10/2/" + y, "9/6/" + y, "10/10/" + y, "10/3/" + y];
var names = ["Mac", "Jac", "Tom", "Abhay", "Mahesh", "Jayesh"];
var months = ["January","February","March","April","May","June","July","August","September","October","November","December"];
for(var i = 0; i < dates.length; i++) {
//document.getElementById("mySup").innerHTML = getGetOrdinal(dates[i].split('/')[0]);
if (datediff(parseDate(dates[i]), (today)) <= 7 && datediff(parseDate(dates[i]), (today)) >= 1)
{
document.getElementById("demo").innerHTML = document.getElementById("demo").innerHTML + "Wish You Happy Birthday, " + names[dates.indexOf(dates[i])] + "!!! (" + getGetOrdinal(dates[i].split('/')[1]) + " " + months[dates[0].split('/')[0]-1]+ ")" + "<br>";
}
}
function getGetOrdinal(n) {
var s=["th","st","nd","rd"],
v=n%100;
return n+(s[(v-20)%10]||s[v]||s[0]);
}
<p><span id="demo"></span><sup id="mySup"></sup><p>
The below answer is what I had to do finally which involves functions, methods, etc. I'm sure it might be helpful to someone.
function parseDate(str) {
var mdy = str.split('/');
return new Date(mdy[2], mdy[0]-1, mdy[1]);
}
// Take the difference between the dates and divide by milliseconds per day.
// Round to nearest whole number to deal with DST.
function datediff(first, second) {
return Math.round((second-first)/(1000*60*60*24));
}
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var y = today.getFullYear();
var dates = ["10/1/" + y, "09/20/" + y, "10/2/" + y, "9/6/" + y, "10/10/" + y, "10/1/" + y];
var names = ["Mac", "Jac", "Tom", "Abhay", "Mahesh", "Jayesh"];
var joingDates = ["10/16/" + y, "09/20/" + y, "10/2/" + y, "9/6/" + y, "10/10/" + y, "10/3/" + y];
var joiningyears = ["2000","2002","2010","2011","2011","2014"];
var months = ["January","February","March","April","May","June","July","August","September","October","November","December"];
for(var i = 0; i < dates.length; i++) {
//document.getElementById("mySup").innerHTML = getGetOrdinal(dates[i].split('/')[0]);
if (datediff(parseDate(dates[i]), (today)) <= 7 && datediff(parseDate(dates[i]), (today)) >= 1)
{
document.getElementById("demo").innerHTML = document.getElementById("demo").innerHTML +
"<li>" +
"Wishing a very" + " Happy Birthday to ".bold().fontcolor("blue") +
names[i].bold().fontcolor("Red") +
"!!! (" +
getGetOrdinal(dates[i].split('/')[1]).split('')[0] +
getGetOrdinal(dates[i].split('/')[1]).split('')[1].sup() +
getGetOrdinal(dates[i].split('/')[1]).split('')[2].sup() +
" " +
months[dates[0].split('/')[0]-1] +
")" +
"<br>";
}
}
for(var i = 0; i < joingDates.length; i++) {
if (datediff(parseDate(joingDates[i]), (today)) <= 7 && datediff(parseDate(joingDates[i]), (today)) >= 1)
{
document.getElementById("demo").innerHTML = document.getElementById("demo").innerHTML +
"<li>" +
"Wishing a very " +
"Happy ".bold().fontcolor("blue") +
getGetOrdinal(y-joiningyears[i]).split('')[0].bold().fontcolor("blue") +
getGetOrdinal(y-joiningyears[i]).split('')[1].sup().bold().fontcolor("blue") +
getGetOrdinal(y-joiningyears[i]).split('')[2].sup().bold().fontcolor("blue") +
" Work Anniversary to ".bold().fontcolor("blue") +
names[i].bold().fontcolor("Red") +
" with " +
"XYZ Company".fontcolor("green").bold() +
"!!! (" +
getGetOrdinal(joingDates[i].split('/')[1]).split('')[0] +
getGetOrdinal(joingDates[i].split('/')[1]).split('')[1].sup() +
getGetOrdinal(joingDates[i].split('/')[1]).split('')[2].sup() +
" " +
months[joingDates[0].split('/')[0]-1] +
")" +
"<br>";
}
}
function getGetOrdinal(n) {
var s=["th","st","nd","rd"],
v=n%100;
return n+(s[(v-20)%10]||s[v]||s[0]);
}
<p id="demo"><p>

Js function working only once

I'm working on a simple javascript photo editor, and I'm stuck on this part:
var opacity = document.getElementById("opacity").value;
var contrast = document.getElementById("contrast").value;
var saturate = document.getElementById("saturate").value;
var brightness = document.getElementById("brightness").value;
var color = document.getElementById("color").value;
var sepia = document.getElementById("sepia").value;
function filter() {
document.getElementById("output").style.filter = "hue-rotate(" + color + "deg) sepia(" + sepia + "%) brightness(" + brightness * 3 + "%) saturate(" + saturate + "%) contrast(" + contrast * 2 + "%)";
}
var filters = document.getElementsByClassName("slider");
for (i = 0; i < filters.length; i++) {
filters[i].addEventListener("click", filter);
}
This function works only once. Similar function for opacity:
function opacity() {
var a = document.getElementById("opacity").value;
document.getElementById("output").style.opacity = a / 10;
}
document.getElementById("opacity").addEventListener("change", opacity);
works fine. Any ideas why? I tried doing it this way:
/*
function contrast() {
var b = document.getElementById("contrast").value;
document.getElementById("output").style.filter = "contrast(" + b * 2 + "%)";
}
document.getElementById("contrast").addEventListener("change", contrast);
function saturate() {
var c = document.getElementById("saturate").value;
document.getElementById("output").style.filter = "saturate(" + c + "%)";
}
document.getElementById("saturate").addEventListener("change", saturate);
function brightness() {
var d = document.getElementById("brightness").value;
document.getElementById("output").style.filter = "brightness(" + d * 3 + "%)";
}
document.getElementById("brightness").addEventListener("change", brightness);
function color() {
var e = document.getElementById("color").value;
document.getElementById("output").style.filter = "hue-rotate(" + e + "deg)";
}
document.getElementById("color").addEventListener("change", color);
function sepia() {
var f = document.getElementById("sepia").value;
document.getElementById("output").style.filter = "sepia(" + c + "%)";
}
document.getElementById("sepia").addEventListener("change", sepia);
/*
And everything is ok, but then I'm unable to apply multiple filters. Any help appreciated!
You have to get the value every time you click
var contrast = document.getElementById("contrast");
var saturate = document.getElementById("saturate");
var brightness = document.getElementById("brightness");
var color = document.getElementById("color");
var sepia = document.getElementById("sepia");
function filter() {
//You have to convert to number to do arithmetic
var _brightness = ~~brightness.value;
document.getElementById("output").style.filter = "hue-rotate(" + color.value + "deg) sepia(" + sepia.value + "%) brightness(" + _brightness * 3 + "%) saturate(" + saturate.value + "%) contrast(" + contrast.value * 2 + "%)";
}
and so on

JS/HTML function

Can someone please help me understand why the function writeOptions logs optionCounter twice?
console.log("<option values=" + optionCounter + ">"+optionCounter);
Why is there a second optionCounter placed after the option element?
<script type = "text/javascript">
function writeOptions(startNumber,endNumber)
{
var optionCounter;
for(optionCounter = startNumber;
optionCounter <= endNumber; optionCounter++)
{
document.write("<option value=" + optionCounter + ">" + optionCounter);
}
}
function writeMonthOptions()
{
var theMonth;
var monthCounter;
var theDate = new Date(1);
for(monthCounter = 0; monthCounter < 12; monthCounter++)
{
theDate.setMonth(monthCounter);
theMonth = theDate.toString();
theMonth = theMonth.substr(4,3);
document.write("<option value=" + theMonth + ">" + theMonth);
}
}
function recalcDateDiff()
{
var myForm = document.form1;
var firstDay =
myForm.firstDay.options[myForm.firstDay.selectedIndex].value;
var secondDay =
myForm.secondDay.options[myForm.secondDay.selectedIndex].value;
var firstMonth =
myForm.firstMonth.options[myForm.firstMonth.selectedIndex].value;
var secondMonth =
myForm.secondMonth.options[myForm.secondMonth.selectedIndex].value;
var firstYear =
myForm.firstYear.options[myForm.firstYear.selectedIndex].value;
var secondYear =
myForm.secondYear.options[myForm.secondYear.selectedIndex].value;
var firstDate =
new Date(firstDay + " " + firstMonth + " " + firstYear);
var secondDate = new Date(secondDay + " " + secondMonth + " " + secondYear);
var daysDiff = (secondDate.valueOf() - firstDate.valueOf());
daysDiff = Math.floor(Math.abs((((daysDiff/1000)/60)/60)/24));
myForm.txtDays.value = daysDiff;
}
function window_onload()
{
var theForm = document.form1;
var nowDate = new Date();
theForm.firstDay.options[nowDate.getDate() - 1].selected =true;
theForm.secondDay.options[nowDate.getDate() - 1].selected = true;
theForm.firstMonth.options[nowDate.getMonth() - 1].selected = true;
theForm.secondMonth.options[nowDate.getMonth() - 1].selected = true;
theForm.firstYear.options[nowDate.getFullYear() - 1970].selected = true;
theForm.secondYear.options[nowDate.getFullYear() - 1970].selected = true;
}
</script>
as you can see this is the entire Javascript codeblock for this particular example.
I believe you know HTML. Each <option> tag has a display text (or label) and a value. And your code is creating the html option tag with both. So, when you write:
document.write("<option value=" + optionCounter + ">" + optionCounter);
the first optionCounter is for value and second one is for label/display text.
Note: I don't see the option tag being closed which could result in issues if not handled properly by the browser, so modify the statement as follows to render correct HTML:
document.write("<option value=" + optionCounter + ">" + optionCounter + "</option>");
Refer more about select tag & option tag on w3schools.com.

How can I center a header above a table according to the table's width (not the entire page's width)?

So here's my code, but I don't know what to add to it to make it center the text according to the tables width.
<script type="text/javascript">
"use strict";
var principal;
var rate;
var numyears;
var yearlist;
var simpleinterest;
var compoundinterest;
yearlist = 1;
principal = Number(prompt("Enter Principal"));
rate = Number(prompt("Enter rate (percentage value)"));
numyears = Number(prompt("Enter number of years"));
document.writeln("<h1>Table for $" + principal + " at " + rate + "%</h1>");
document.writeln("<table id=\"interest\"><th>Year</th><th>SimpleInterest</th><th>CompoundInterest</th>");
while (yearlist <= numyears) {
compoundinterest = Math.pow((1+rate/100), yearlist) * principal;
simpleinterest = (principal * yearlist * rate/100) + principal;
document.writeln("<tr><td>" + yearlist + "</td><td>$" + simpleinterest + "</td><td>$" + compoundinterest + "</td></tr>");
yearlist++;
}
</script>
Your question is not clear. but on a guess, I had created this
<script type="text/javascript">
"use strict";
var principal;
var rate;
var numyears;
var yearlist;
var simpleinterest;
var compoundinterest;
yearlist = 1;
principal = Number(prompt("Enter Principal"));
rate = Number(prompt("Enter rate (percentage value)"));
numyears = Number(prompt("Enter number of years"));
document.writeln("<table id=\"interest\">");
document.writeln("<tr><td colspan='3' align='center'><h1 align='center'>Table for $" + principal + " at " + rate + "%</h1></td></tr><th>Year</th><th>SimpleInterest</th><th>CompoundInterest</th>");
while (yearlist <= numyears) {
compoundinterest = Math.pow((1+rate/100), yearlist) * principal;
simpleinterest = (principal * yearlist * rate/100) + principal;
document.writeln("<tr><td>" + yearlist + "</td><td>$" + simpleinterest + "</td><td>$" + compoundinterest + "</td></tr>");
yearlist++;
}
</script>

Categories

Resources