auto calculate multiple dropdown selection - javascript

i am trying to generate total from dropdown selected values using html and JavaScript, my code is working. but when i an changing my choices from dropdown i want the total to be changed on every dropdown selection. But its not happening.
like if i am entering value in after tax income and selecting fortnightly in dropdown, the total changes. but when am entering second and third value and setting them monthly and weekly respectively, it doesnt change according to selection.
where could be the problem?
<script>
function asum() {
var first = document.getElementById('a1').value;
if (document.getElementById('a1').value == "") {
var first = 0;
}
var second = document.getElementById('a2').value;
if (document.getElementById('a2').value == "") {
var second = 0;
}
var third = document.getElementById('a3').value;
if (document.getElementById('a3').value == "") {
var third = 0;
}
var forth = document.getElementById('fc4').value;
if (document.getElementById('fc4').value == "") {
var forth = 0;
}
var fifth = document.getElementById('fc5').value;
if (document.getElementById('fc5').value == "") {
var fifth = 0;
}
var aresult = parseInt(first) + parseInt(second) + parseInt(third);
//aduration1
if (document.getElementById('aduration3').value == "Monthly") {
var aweekly = parseInt((aresult * 12) / 52);
if (!isNaN(aresult)) {
document.getElementById('a4').value = aweekly;
}
}
if (document.getElementById('aduration3').value == "Fortnightly") {
var weekly = parseInt((aresult * 26) / 52);
if (!isNaN(aresult)) {
document.getElementById('a4').value = weekly;
}
}
if (document.getElementById('aduration3').value == "Weekly") {
if (!isNaN(aresult)) {
document.getElementById('a4').value = parseInt(aresult);
}
}
//aduration2
if (document.getElementById('aduration2').value == "Monthly") {
var aweekly = parseInt((aresult * 12) / 52);
if (!isNaN(aresult)) {
document.getElementById('a4').value = aweekly;
}
}
if (document.getElementById('aduration2').value == "Fortnightly") {
var weekly = parseInt((aresult * 26) / 52);
if (!isNaN(aresult)) {
document.getElementById('a4').value = weekly;
}
}
if (document.getElementById('aduration2').value == "Weekly") {
if (!isNaN(aresult)) {
document.getElementById('a4').value = parseInt(aresult);
}
}
//aduration3
if (document.getElementById('aduration3').value == "Monthly") {
var aweekly = parseInt((aresult * 12) / 52);
if (!isNaN(aresult)) {
document.getElementById('a4').value = aweekly;
}
}
if (document.getElementById('aduration3').value == "Fortnightly") {
var weekly = parseInt((aresult * 26) / 52);
if (!isNaN(aresult)) {
document.getElementById('a4').value = weekly;
}
}
if (document.getElementById('aduration3').value == "Weekly") {
if (!isNaN(aresult)) {
document.getElementById('a4').value = parseInt(aresult);
}
}
}
</script>
<div>
<center>
<table cellpadding="5px" style="border: 1px solid !important; padding: 10px !important;width: 40% !important;">
<tr>
<td style="width: 25%;">
<label>After tax salary</label>
</td>
<td style="width: 20%;">
<input type="text" id="a1" placeholder="$" vlaue="0" onkeyup="asum();" />
</td>
<td style="width: 15%;">
<select id="aduration3" name="aduration3" onchange="asum();">
<option value="Monthly">Monthly</option>
<option value="Fortnightly">Fortnightly</option>
<option value="Weekly">Weekly</option>
</select>
</td>
<td style="width: 41%;">
</td>
</tr>
<tr>
<td>
<label>Net passive income</label>
</td>
<td>
<input type="text" id="a2" placeholder="$" onkeyup="asum();" />
</td>
<td>
<select id="aduration2" name="aduration2" onchange="asum();">
<option value="Monthly">Monthly</option>
<option value="Fortnightly">Fortnightly</option>
<option value="Weekly">Weekly</option>
</select>
</td>
<td>
</td>
</tr>
<tr>
<td>
<label>Other income</label>
</td>
<td>
<input type="text" id="a3" placeholder="$" onkeyup="asum();" />
</td>
<td>
<select id="aduration1" name="aduration1" onchange="asum();">
<option value="Monthly">Monthly</option>
<option value="Fortnightly">Fortnightly</option>
<option value="Weekly">Weekly</option>
</select>
</td>
<td>
</td>
</tr>
<tr>
<td>
</td>
<td colspan="2">
<input type="text" id="a4" placeholder="$" onclick="asum();" style="height: 30px !important; margin-top: 3px; margin-bottom: 3px;" />
</td>
<td>
<label><b style="font-size:16px;" onclick="asum();"><u>TOTAL WEEKLY INCOME</u></b>
<label>
</td>
</tr>
<tr>
<td>
</td>
<td colspan="2">
<input type="phone" id="a5" placeholder="$" onclick="bsum();" onkeyup="bsum();" style="height:30px !important;" />
</td>
<td>
<label><b style="font-size:16px;" onclick="bsum();"><u>TOTAL WEEKLY SURPLUS</u></b></label>
</td>
</tr>
</table>
</center>
</div>

You can do all of your calculation with few simple lines of code in jQuery:
$(':input').on('change blur keyup', function(){
var a = parseInt($('#a1').val()) || 0;
var b = parseInt($('#a2').val()) || 0;
var c = parseInt($('#a3').val()) || 0;
var aresult = a + b + c;
var ad2 = $('#aduration2').val();
var ad3 = $('#aduration3').val();
switch(ad2){
case 'Monthly':
$('#a4').val( (aresult * 12) / 52 );
break;
case 'Fortnightly':
$('#a4').val( (aresult * 26) / 52 );
break;
case 'Weekly':
$('#a4').val( aresult );
break;
}
switch(ad3){
case 'Monthly':
$('#a5').val( (aresult * 12) / 52 );
break;
case 'Fortnightly':
$('#a5').val( (aresult * 26) / 52 );
break;
case 'Weekly':
$('#a5').val( aresult );
break;
}
});
Fiddle HERE
PS in your code you mentioned #aduration1 which is not present in you're HTML, and your making double calculation for #aduration3

<code>
$(':input').on('change blur', function(){
var a = parseInt($('#a1').val()) || 0;
var b = parseInt($('#a2').val()) || 0;
var c = parseInt($('#a3').val()) || 0;
var aresult = a + b + c;
var ad1 = $('#aduration1').val();
var ad2 = $('#aduration2').val();
var ad3 = $('#aduration3').val();
switch(ad1){
case 'Monthly':
$('#a4').val( (aresult * 12) / 52 );
break;
case 'Fortnightly':
$('#a4').val( (aresult * 26) / 52 );
break;
case 'Weekly':
$('#a4').val( aresult );
break;
}
switch(ad2){
case 'Monthly':
$('#a4').val( (aresult * 12) / 52 );
break;
case 'Fortnightly':
$('#a4').val( (aresult * 26) / 52 );
break;
case 'Weekly':
$('#a4').val( aresult );
break;
}
switch(ad3){
case 'Monthly':
$('#a4').val( (aresult * 12) / 52 );
break;
case 'Fortnightly':
$('#a4').val( (aresult * 26) / 52 );
break;
case 'Weekly':
$('#a4').val( aresult );
break;
}
});

Related

Trouble with updating an HTML table using javascript

I looked through a few questions on here but none of them seems to be showing the problem that I am having.
The Problem:
I have a business case question where we are asked to build a simple calculator for a business pricing model using HTML/Javascript/CSS.
I'm still a beginner to these languages but have good experience in other languages.
I have been through google and stack overflow, all of which are telling me to use the "document.GetElementById()" function.
I have tried implementing this function however I must be doing something wrong because when I press submit nothing happens.
I apologise for the following being a long code block but I can't be sure where my error actually is.
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Business Case Calculator</title>
<script>
function displayTable() {
let boxStr = document.getElementById("number");
if (boxStr != '') {
numOfEmps = parseInt(boxStr);
if (numOfEmps < 1) {
numOfEmps = 1;
}
}
switch (true) {
case numOfEmps <= 12:
prices = bracket1(numOfEmps);
case numOfEmps <= 50:
prices = bracket2(numOfEmps);
case numOfEmps <= 250:
prices = bracket3(numOfEmps);
}
document.getElementById("mojo-price").innerHTML = String(prices[0]);
document.getElementById("wiredup-price").innerHTML = String(prices[1]);
document.getElementById("workwith-price").innerHTML = String(prices[2]);
document.getElementById("063-price").innerHTML = String(prices[3]);
document.getElementById("total-price").innerHTML = String(prices[4]);
function bracket1(numOfEmps) {
let mojo = 0;
let wiredUp = numOfEmps * 75;
let workWith = numOfEmps * 75;
let the063 = numOfEmps * 250;
let totalPrice = mojo + wiredUp + workWith + the063;
return [mojo, wiredUp, workWith, the063, totalPrice];
}
function bracket2(numOfEmps) {
let mojo = 0;
let wiredUp = numOfEmps * 60;
let workWith = numOfEmps * 60;
let the063 = numOfEmps * 200;
let totalPrice = mojo + wiredUp + workWith + the063;
return [mojo, wiredUp, workWith, the063, totalPrice];
}
function bracket3(numOfEmps) {
let mojo = 0;
let wiredUp = numOfEmps * 54;
let workWith = numOfEmps * 54;
let the063 = numOfEmps * 180;
let totalPrice = mojo + wiredUp + workWith + the063;
return [mojo, wiredUp, workWith, the063, totalPrice];
}
}
</script>
</head>
<body>
<div class="input">
<form class="input-form" id="cpcalc">
<input type="text" placeholder="30" id="number">
</form>
<button type="button" onclick="displayTable();">Submit</button>
</div>
<div>
<table>
<tr>
<td>
Profiler
</td>
<td>
Price
</td>
</tr>
<tr>
<td>
Mojo
</td>
<td>
<!--Mojo Price-->
<span id="mojo-price">
</span>
</td>
</tr>
<tr>
<td>
Wired Up
</td>
<td>
<!--Wired Up Price-->
<span id="wiredup-price">
</span>
</td>
</tr>
<tr>
<td>
Work With
</td>
<td>
<!--Work With Price-->
<span id="workwith-price">
</span>
</td>
</tr>
<tr>
<td>
063 | 360
</td>
<td>
<!--063 Price-->
<span id="063-price">
</span>
</td>
</tr>
<tr>
<td>
<!--Blank-->
</td>
<td>
<!--Blank-->
</td>
</tr>
<tr>
<td>
Total
</td>
<td>
<!--Total Price-->
<span id="total-price">
</span>
</td>
</body>
</html>
What I am hoping happens is that the table is populated with the calculated prices correctly.
I will be dealing with the CSS side of the question once the functionality works.
You were not defining prices before using it and you were reading the reference to the input element itself, not its value (document.getElementById("number").value).
Here you go:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Business Case Calculator</title>
<script>
function displayTable() {
let prices = []
let boxStr = document.getElementById("number").value
if (boxStr != '') {
numOfEmps = parseInt(boxStr);
if (numOfEmps < 1) {
numOfEmps = 1;
}
}
switch (true) {
case numOfEmps <= 12:
prices = bracket1(numOfEmps);
case numOfEmps <= 50:
prices = bracket2(numOfEmps);
case numOfEmps <= 250:
prices = bracket3(numOfEmps);
}
document.getElementById("mojo-price").innerHTML = String(prices[0]);
document.getElementById("wiredup-price").innerHTML = String(prices[1]);
document.getElementById("workwith-price").innerHTML = String(prices[2]);
document.getElementById("063-price").innerHTML = String(prices[3]);
document.getElementById("total-price").innerHTML = String(prices[4]);
}
function bracket1(numOfEmps) {
let mojo = 0;
let wiredUp = numOfEmps * 75;
let workWith = numOfEmps * 75;
let the063 = numOfEmps * 250;
let totalPrice = mojo + wiredUp + workWith + the063;
console.log(numOfEmps)
return [mojo, wiredUp, workWith, the063, totalPrice];
}
function bracket2(numOfEmps) {
let mojo = 0;
let wiredUp = numOfEmps * 60;
let workWith = numOfEmps * 60;
let the063 = numOfEmps * 200;
let totalPrice = mojo + wiredUp + workWith + the063;
return [mojo, wiredUp, workWith, the063, totalPrice];
}
function bracket3(numOfEmps) {
let mojo = 0;
let wiredUp = numOfEmps * 54;
let workWith = numOfEmps * 54;
let the063 = numOfEmps * 180;
let totalPrice = mojo + wiredUp + workWith + the063;
return [mojo, wiredUp, workWith, the063, totalPrice];
}
</script>
</head>
<body>
<div class="input">
<form class="input-form" id="cpcalc">
<input type="text" placeholder="30" id="number">
</form>
<button type="button" onclick="displayTable();">Submit</button>
</div>
<div>
<table>
<tr>
<td>
Profiler
</td>
<td>
Price
</td>
</tr>
<tr>
<td>
Mojo
</td>
<td>
<!--Mojo Price-->
<span id="mojo-price">
</span>
</td>
</tr>
<tr>
<td>
Wired Up
</td>
<td>
<!--Wired Up Price-->
<span id="wiredup-price">
</span>
</td>
</tr>
<tr>
<td>
Work With
</td>
<td>
<!--Work With Price-->
<span id="workwith-price">
</span>
</td>
</tr>
<tr>
<td>
063 | 360
</td>
<td>
<!--063 Price-->
<span id="063-price">
</span>
</td>
</tr>
<tr>
<td>
<!--Blank-->
</td>
<td>
<!--Blank-->
</td>
</tr>
<tr>
<td>
Total
</td>
<td>
<!--Total Price-->
<span id="total-price">
</span>
</td>
</body>
</html>
A hint I would give you is to console.log() (a.k.a. print) everything to understand the state of your data. Modern browses also have very powerful JavaScript debuggers too, so you can use breakpoints, print objects as tables, edit values during execution and all that. For Firefox and Chrome you can call it with Ctrl + Shift + I.
You dont have to use String constructor. innerHTML can contains both numbers and strings. Also, you can use textContent cause you don't insert any of html in there. As previous answers said, you haven't ever define prices.
Check html5 input docs. There are many arguments that can help you to control over the input values or validation. As you can see required attribute for input prevents of living this field empty and type number is tell that this field accept only numbers. Also there are min and max attributes< I guess you find out what they do)
let prices = {
mojo: {
coefs: {
1: 0,
2: 0,
3: 0
},
price: 0
},
wiredup: {
coefs: {
1: 75,
2: 60,
3: 54
},
price: 0
},
workwith: {
coefs: {
1: 75,
2: 60,
3: 54
},
price: 0
},
the063: {
coefs: {
1: 200,
2: 250,
3: 180
},
price: 0
}
}
let totalPrice = getTotalPrice()
const numberEl = document.querySelector('#number')
setTableValues()
function displayTable() {
let value = numberEl.value
if (value <= 12) {
getPriceForBracket(value, 1);
} else if (value <= 50) {
getPriceForBracket(value, 2)
} else if (value <= 250) {
getPriceForBracket(value, 3)
}
setTableValues()
}
function getPriceForBracket(value, bracket) {
Object.keys(prices).forEach(key => {
prices[key].price = value * prices[key].coefs[bracket]
})
}
function getTotalPrice() {
return Object.values(prices).reduce((res, val) => res + val.price, 0)
}
function setTableValues() {
Object.keys(prices).forEach(key => {
document.querySelector(`#${key}-price`).textContent = prices[key].price
document.querySelector('#total-price').textContent = getTotalPrice()
})
}
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Business Case Calculator</title>
</head>
<body>
<div class="input">
<form class="input-form" id="cpcalc">
<input type="number" placeholder="30" id="number" value="1" min="0" max="9999" required>
</form>
<button type="button" onclick="displayTable()">Submit</button>
</div>
<div>
<table>
<tr>
<td>
Profiler
</td>
<td>
Price
</td>
</tr>
<tr>
<td>
Mojo
</td>
<td>
<!--Mojo Price-->
<span id="mojo-price">
</span>
</td>
</tr>
<tr>
<td>
Wired Up
</td>
<td>
<!--Wired Up Price-->
<span id="wiredup-price">
</span>
</td>
</tr>
<tr>
<td>
Work With
</td>
<td>
<!--Work With Price-->
<span id="workwith-price">
</span>
</td>
</tr>
<tr>
<td>
063 | 360
</td>
<td>
<!--063 Price-->
<span id="the063-price">
</span>
</td>
</tr>
<tr>
<td>
<!--Blank-->
</td>
<td>
<!--Blank-->
</td>
</tr>
<tr>
<td>
Total
</td>
<td>
<!--Total Price-->
<span id="total-price">
</span>
</td>
</body>
</html>
Telmo's answer addresses the core of your problem, and he should get the accepted tick IMO. I've just refactored it down to reduce the amount of repeated code. I've used a couple of objects, one to store the brackets and another to store the final prices.
const brackets = {
one: {
mojo: 0,
wiredUp: 75,
workWith: 75,
the063: 250
},
two: {
mojo: 0,
wiredUp: 60,
workWith: 60,
the063: 200
},
three: {
mojo: 0,
wiredUp: 54,
workWith: 54,
the063: 180
}
}
function displayTable() {
let prices = {
"mojo": "",
"wiredUp": "",
"workWith": "",
"Zero63": "",
"total": ""
};
let bracket = {};
let boxStr = document.getElementById("number").value
if (boxStr != '') {
numOfEmps = parseInt(boxStr);
if (numOfEmps < 1) {
numOfEmps = 1;
}
}
switch (true) {
case numOfEmps <= 12:
bracket = brackets.one
case numOfEmps <= 50:
bracket = brackets.two
case numOfEmps <= 250:
bracket = brackets.three
}
prices.mojo = bracket.mojo;
prices.wiredUp = numOfEmps * bracket.wiredUp;
prices.workWith = numOfEmps * bracket.workWith;
prices.Zero63 = numOfEmps * bracket.the063;
prices.total = prices.mojo + prices.wiredUp + prices.workWith + prices.Zero63;
document.getElementById("mojo-price").textContent = String(prices.mojo);
document.getElementById("wiredup-price").textContent = String(prices.wiredUp);
document.getElementById("workwith-price").textContent = String(prices.workWith);
document.getElementById("063-price").textContent = String(prices.Zero63);
document.getElementById("total-price").textContent = String(prices.total);
}
<div class="input">
<form class="input-form" id="cpcalc">
<input type="text" placeholder="30" id="number">
</form>
<button type="button" onclick="displayTable();">Submit</button>
</div>
<div>
<table>
<tr>
<td>
Profiler
</td>
<td>
Price
</td>
</tr>
<tr>
<td>
Mojo
</td>
<td>
<!--Mojo Price-->
<span id="mojo-price">
</span>
</td>
</tr>
<tr>
<td>
Wired Up
</td>
<td>
<!--Wired Up Price-->
<span id="wiredup-price">
</span>
</td>
</tr>
<tr>
<td>
Work With
</td>
<td>
<!--Work With Price-->
<span id="workwith-price">
</span>
</td>
</tr>
<tr>
<td>
063 | 360
</td>
<td>
<!--063 Price-->
<span id="063-price">
</span>
</td>
</tr>
<tr>
<td>
<!--Blank-->
</td>
<td>
<!--Blank-->
</td>
</tr>
<tr>
<td>
Total
</td>
<td>
<!--Total Price-->
<span id="total-price">
</span>
</td>

document.getElementById() doesnt work properly

I have 20 unique random numbers and check between 6 unique numbers.
the first check works, but after refreshing the 6 unique numbers, of the numbers return undefined.
I've given the full code so people can tinker with it.
no need for CSS, that is just to identify different numbers.
sorry for the long codes, it's just how i keep my code tidy.
var num = [];
var com = [];
var s = 0;
var j = 0;
function twenty() {
for (i = 0; i < 20; i++) {
com[i] = Math.floor(Math.random() * 49) + 1;
var x = com.length;
x = x - 1;
for (y = 0; y < x; y++) {
var t1 = com[y];
var t2 = com[i]
while (t1 == t2) {
com[x] = Math.floor(Math.random() * 49) + 1;
t1 = com[x];
}
}
}
for (i = 0; i < 5; i++) {
for (t = 0; t < 4; t++) {
document.getElementsByClassName(t)[i].innerHTML = com[s];
s++;
}
}
}
function calc() {
num = [];
var out = "";
var z = document.getElementById('max').value;
for (i = 0; i < z; i++) {
num[i] = Math.floor(Math.random() * 49) + 1;
var x = num.length;
x = x - 1;
for (y = 0; y < x; y++) {
var t1 = num[y];
var t2 = num[i]
while (t1 == t2) {
num[x] = Math.floor(Math.random() * 49) + 1;
t1 = num[x];
}
}
out += num[i] + ", ";
}
document.getElementById('num').innerHTML = out;
}
function check() {
s = 0;
if (j == 0) {
for (i = 0; i < 5; i++) {
for (t = 0; t < 4; t++) {
var set = 0;
var test1 = document.getElementsByClassName(t)[i].innerHTML;
var y = num.length;
for (x = 0; x < y; x++) {
var comp = num[x];
if (test1 == comp) {
set = 1;
}
if (set == 1) {
document.getElementsByClassName(t)[i].innerHTML = "<input type='button' value = '" + com[s] + "' id='" + s + "' class='yes' >";
} else if (test1 == undefined) {
document.getElementsByClassName(t)[i].innerHTML = "undefined";
} else {
document.getElementsByClassName(t)[i].innerHTML = "<input type='button' value = '" + com[s] + "' id='" + s + "' class='no' >";
}
}
s++;
}
}
j = 1;
} else {
for (i = 0; i < 5; i++) {
for (t = 0; t < 4; t++) {
var set = 0;
var test1 = document.getElementById(s).value;
var y = num.length;
for (x = 0; x < y; x++) {
var comp = num[x];
if (test1 == comp) {
set = 1;
}
if (set == 1) {
document.getElementsByClassName(t)[i].innerHTML = "<input type='button' value = '" + com[s] + "' id='" + s + "' class='yes' >";
} else if (test1 == undefined) {
document.getElementsByClassName(t)[i].innerHTML = "undefined";
} else {
document.getElementsByClassName(t)[i].innerHTML = "<input type='button' value = '" + com[s] + "' id='" + s + "' class='no' >";
}
}
s++;
}
}
}
}
html{
}
input[type=button].yes{
background: green;
border: none;
}
input[type=button].no{
background: red;
border: none;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
<script src='code.js'></script>
</head>
<body onload='twenty()'>
<h1>lottery randomizer</h1>
<table border='1'>
<tr>
<td>randomize numbers
</td>
<td>choose number of random numbers
</td>
</tr>
<tr>
<td>
<input type='button' onclick='calc()' value='randomize'>
</td>
<td>
<input type='number' value='6' id='max'>
</td>
</tr>
</table>
<table>
<tr>
<td>
your numbers are:
<div id='num'>
</div>
</td>
</tr>
</table>
<table border='1' class='table'>
<tr>
<td>
<div class='0' id='1'>
</div>
</td>
<td>
<div class='0' id='2'>
</div>
</td>
<td>
<div class='0' id='3'>
</div>
</td>
<td>
<div class='0' id='4'>
</div>
</td>
<td>
<div class='0' id='5'>
</div>
</td>
</tr>
<tr>
<td>
<div class='1' id='1'>
</div>
</td>
<td>
<div class='1' id='2'>
</div>
</td>
<td>
<div class='1' id='3'>
</div>
</td>
<td>
<div class='1' id='4'>
</div>
</td>
<td>
<div class='1' id='5'>
</div>
</td>
</tr>
<tr>
<td>
<div class='2'>
</div>
</td>
<td>
<div class='2'>
</div>
</td>
<td>
<div class='2'>
</div>
</td>
<td>
<div class='2'>
</div>
</td>
<td>
<div class='2'>
</div>
</td>
</tr>
<tr>
<td>
<div class='3' id='1'>
</div>
</td>
<td>
<div class='3' id='2'>
</div>
</td>
<td>
<div class='3' id='3'>
</div>
</td>
<td>
<div class='3' id='4'>
</div>
</td>
<td>
<div class='3' id='5'>
</div>
</td>
</tr>
</table>
<input type='button' onclick='check()' value='check numbers'>
</body>
</html>

How to get remaining days for certain birthday?

When I'm calculating my age, the code below showing "xxx days left for your next birthday". But I want to know, how many days left for my certain birthday. (i.e: I want to know how many days left for my 30th birthday. The result should be like this "xxx days left for your 30th birthday" instead of next birthday.)
What change I need to do?
function wr_document() {
var w = new Date();
var s_d = w.getDate();
var s_m = w.getMonth() + 1;
var s_y = w.getFullYear();
document.cir.len11.value = s_d;
document.cir.len12.value = s_m;
document.cir.len13.value = s_y;
}
function isNum(arg) {
var args = arg;
if (args == "" || args == null || args.length == 0) {
return false;
}
args = args.toString();
for (var i = 0; i < args.length; i++) {
if ((args.substring(i, i + 1) < "0" || args.substring(i, i + 1) > "9") && args.substring(i, i + 1) != ".") {
return false;
}
}
return true;
}
function checkday(aa) {
var val = aa.value;
var valc = val.substring(0, 1);
if (val.length > 0 && val.length < 3) {
if (!isNum(val) || val == 0) {
aa.value = "";
} else if (val < 1 || val > 31) {
aa.value = valc;
}
} else if (val.length > 2) {
val = val.substring(0, 2);
aa.value = val;
}
}
function checkmon(aa) {
var val = aa.value;
var valc = val.substring(0, 1);
if (val.length > 0 && val.length < 3) {
if (!isNum(val) || val == 0) {
aa.value = "";
} else if (val < 1 || val > 12) {
aa.value = valc;
}
} else if (val.length > 2) {
val = val.substring(0, 2);
aa.value = val;
}
}
function checkyear(aa) {
var val = aa.value;
var valc = val.substring(0, (val.length - 1));
if (val.length > 0 && val.length < 7) {
if (!isNum(val) || val == 0) {
aa.value = valc;
} else if (val < 1 || val > 275759) {
aa.value = "";
}
} else if (val.length > 4) {
aa.value = valc;
}
}
function checkleapyear(datea) {
if (datea.getYear() % 4 == 0) {
if (datea.getYear() % 10 != 0) {
return true;
} else {
if (datea.getYear() % 400 == 0)
return true;
else
return false;
}
}
return false;
}
function DaysInMonth(Y, M) {
with(new Date(Y, M, 1, 12)) {
setDate(0);
return getDate();
}
}
function datediff(date1, date2) {
var y1 = date1.getFullYear(),
m1 = date1.getMonth(),
d1 = date1.getDate(),
y2 = date2.getFullYear(),
m2 = date2.getMonth(),
d2 = date2.getDate();
if (d1 < d2) {
m1--;
d1 += DaysInMonth(y2, m2);
}
if (m1 < m2) {
y1--;
m1 += 12;
}
return [y1 - y2, m1 - m2, d1 - d2];
}
function calage() {
var curday = document.cir.len11.value;
var curmon = document.cir.len12.value;
var curyear = document.cir.len13.value;
var calday = document.cir.len21.value;
var calmon = document.cir.len22.value;
var calyear = document.cir.len23.value;
if (curday == "" || curmon == "" || curyear == "" || calday == "" || calmon == "" || calyear == "") {
alert("Please fill all the values and click 'Go'");
} else if (curday == calday && curmon == calmon && curyear == calyear) {
alert("Today your birthday & Your age is 0 years old")
} else {
var curd = new Date(curyear, curmon - 1, curday);
var cald = new Date(calyear, calmon - 1, calday);
var diff = Date.UTC(curyear, curmon, curday, 0, 0, 0) -
Date.UTC(calyear, calmon, calday, 0, 0, 0);
var dife = datediff(curd, cald);
document.cir.val.value = dife[0] + " years, " + dife[1] + " months, and " + dife[2] + " days";
var secleft = diff / 1000 / 60;
document.cir.val3.value = secleft + " minutes since your birth";
var hrsleft = secleft / 60;
document.cir.val2.value = hrsleft + " hours since your birth";
var daysleft = hrsleft / 24;
document.cir.val1.value = daysleft + " days since your birth";
//alert(""+parseInt(calyear)+"--"+dife[0]+"--"+1);
var as = parseInt(calyear) + dife[0] + 1;
var diff = Date.UTC(as, calmon, calday, 0, 0, 0) -
Date.UTC(curyear, curmon, curday, 0, 0, 0);
var datee = diff / 1000 / 60 / 60 / 24;
document.cir.val4.value = datee + " days left for your next birthday";
}
}
function color(test) {
for (var j = 7; j < 12; j++) {
var myI = document.getElementsByTagName("input").item(j);
//myI.setAttribute("style",ch);
myI.style.backgroundColor = test;
}
}
function color1(test) {
var myI = document.getElementsByTagName("table").item(0);
//myI.setAttribute("style",ch);
myI.style.backgroundColor = test;
}
.cal-container {
width: 540px;
margin: 10px auto 0;
}
#age-calculator {
background: none repeat scroll 0 0 #DDDDDD;
border: 1px solid #BEBEBE;
padding-left: 20px;
}
.calc {
border-color: #AAAAAA #999999 #929292 #AAAAAA;
border-style: solid;
border-width: 1px 2px 2px 1px;
padding: 2px 30px 3px;
height: 27px;
}
.calc:active {
border-color: #AAAAAA #999999 #929292 #AAAAAA;
border-style: solid;
border-width: 1px;
}
<title>Age calculator </title>
<body onload="wr_document()">
<div class="cal-container">
<div id="calculator-container">
<table border="0" cellpadding="0" cellspacing="0" style="width: 100%px;">
<tbody>
<tr>
<td valign="top">
<h1 style="padding-top: 10px;">
Age Calculator</h1>
<div class="descalign">
<span>Calculate your age in days, years, minutes, seconds. Know how many days are left for your next birthday.</span><br /><br />
</div>
<div id="age-calculator">
<table bgcolor="" border="0" cellpadding="0" cellspacing="4" style="width: 100%px;">
<tbody>
<tr>
<td colspan="2">
<table class="result" style="height: 100%px; width: 100%px;">
<tbody>
<tr>
<td>
<form name="cir">
<table cellpadding="3" cellspacing="0">
<tbody>
<tr>
<td colspan="2">
<br /> Today's Date is:
</td>
</tr>
<tr>
<td align="center" colspan="2">
Date -
<input class="innerc resform" name="len11" onkeyup="checkday(this)" size="2" type="text" value="" /> Month -
<input class="innerc resform" name="len12" onkeyup="checkmon(this)" size="2" type="text" value="" /> Year -
<input class="innerc resform" name="len13" onkeyup="checkyear(this)" size="4" type="text" value="" />
<br />
<br />
</td>
</tr>
<tr>
<td colspan="2"> Enter Your Date of Birth : </td>
</tr>
<tr>
<td align="center" colspan="2">
Date -
<input class="innerc resform" name="len21" onkeyup="checkday(this)" size="2" type="text" /> Month -
<input class="innerc resform" name="len22" onkeyup="checkmon(this)" size="2" type="text" /> Year -
<input class="innerc resform" name="len23" onkeyup="checkyear(this)" size="4" type="text" />
<br />
<br />
<input class="calc" name="but" onclick="calage()" type="button" value=" Go " />
<br />
<br />
</td>
</tr>
<tr>
<td align="center" class="form" width="30%">
<b> </b>
</td>
</tr>
</tbody>
</table>
<table>
<tbody>
<tr>
<td>
<b> Your Age is </b>
</td>
<td>
<input class="resform" name="val" readonly="" size="36" type="text" />
</td>
</tr>
<tr>
<td>
<b> Your Age in Days </b>
</td>
<td>
<input class="resform" name="val1" readonly="" size="36" type="text" />
</td>
</tr>
<tr>
<td>
<b> Your Age in Hours </b>
</td>
<td>
<input class="resform" name="val2" readonly="" size="36" type="text" /> (Approximate)
</td>
</tr>
<tr>
<td class="form">
<b> Your Age in Minutes </b>
</td>
<td>
<input class="resform" name="val3" readonly="" size="36" type="text" /> (Approximate)
</td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td></td>
<td>
<input class="innerc resform" name="val4" readonly="" size="36" type="text" />
</td>
</tr>
</tbody>
</table>
</form>
</td>
</tr>
</tbody>
</table>
<br />
</td>
<td> </td>
</tr>
<tr>
<td align="right" colspan="2"> </td>
<td> </td>
</tr>
</tbody>
</table>
<br />
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
Not clear about purpose of your whole code, but based on your question following script may help you.
// Let below variables store your birth date
var day = 13;
var month = 03;
var year = 1993;
var x = 30; // Finding 30th birthday
var xthBirthday = new Date((year + x), (month - 1), day); // As month starts with 0
var timeForXthBirthday = xthBirthday.getTime() - Date.now();
var noOfDaysForXthBirthday = Math.ceil(timeForXthBirthday / (1000 * 60 * 60 * 24)); // No. of days left for your xth birthday
document.write(noOfDaysForXthBirthday+" days left for your "+x+"<sup>th</sup> birthday.");
Hope this helps.

Calculating GPA and Credit Hours

<script type="text/javascript">
<!--Hide from old browsers
function gpacalc() {
var grade = new Array(9);
var credit = new Array(9);
var getGrade = new Array(5);
var getCredit = new Array(5);
var gradeCount = 12;
grade[0] = "A+";
credit[0] = 4;
grade[1] = "A";
credit[1] = 4;
grade[2] = "A-";
credit[2] = 3.7;
grade[3] = "B+";
credit[3] = 3.3;
grade[4] = "B";
credit[4] = 3;
grade[5] = "B-";
credit[5] = 2.7;
grade[6] = "C+";
credit[6] = 2;
grade[7] = "C-";
credit[7] = 1.7;
grade[8] = "D+";
credit[8] = 1.3;
grade[9] = "D";
credit[9] = 1;
grade[10] = "D-";
credit[10] = 0.7;
grade[11] = "F";
credit[11] = 0.0;
getGrade[0] = document.calcGpaForm.grade1.value;
getGrade[0] = getGrade[0].toUpperCase();
getGrade[1] = document.calcGpaForm.grade2.value;
getGrade[1] = getGrade[1].toUpperCase();
getGrade[2] = document.calcGpaForm.grade3.value;
getGrade[2] = getGrade[2].toUpperCase();
getGrade[3] = document.calcGpaForm.grade4.value;
getGrade[3] = getGrade[3].toUpperCase();
getGrade[4] = document.calcGpaForm.grade5.value;
getGrade[4] = getGrade[4].toUpperCase();
getGrade[5] = document.calcGpaForm.grade6.value;
getGrade[5] = getGrade[5].toUpperCase();
getCredit[0] = document.calcGpaForm.credit1.value;
getCredit[1] = document.calcGpaForm.credit2.value;
getCredit[2] = document.calcGpaForm.credit3.value;
getCredit[3] = document.calcGpaForm.credit4.value;
getCredit[4] = document.calcGpaForm.credit5.value;
getCredit[5] = document.calcGpaForm.credit6.value;
var totalGrades =0;
var totalCredits = 0;
var GPA = 0;
var i = 0;
for (i; i < 6; i++) {
if (getGrade[i] == "") {
break;
}
else if (getGrade[i] == "c" || getGrade[i] == "C") {
alert("'C' is not a vaild letter grade. Course " +eval(i + 1)+ ".")
return;
}
else if (isNaN(getCredit[i])) {
alert("Enter a vaild number of credits for Course " +eval(i + 1)+ ".")
return;
}
else if (getCredit[i] == "") {
alert ("You left the number of credits blank for Course " +eval(i + 1)+ ".")
return;
}
var validgradecheck = 0;
var x = 0;
for (x; x < gradeCount; x++) {
if (getGrade[i] == grade[x]) {
totalGrades = totalGrades + (parseInt(getCredit[i],10) * credit[x]);
totalCredits = totalCredits + parseInt(getCredit[i],10);
validgradecheck = 1;
break;
}
}
if (validgradecheck == 0) {
alert("Could not recognize the grade entered for Course " +eval(i + 1)+ ".");
return;
}
}
if (totalCredits == 0) {
alert("Total credits cannot equal zero.");
return;
}
GPA = Math.round(( totalGrades / totalCredits ) * 100) / 100;
alert("GPA = " + eval(GPA));
return;
}
function copyRight() {
var lastModDate = document.lastModified;
var lastModDate = lastModDate.substring(0,10);
displayDateLast.innerHTML = "<h6>Copyright © Haiwook Choi. "+" <br /> This document was last modified "+lastModDate+".</h6>";
}
//-->
</script>
<style type="text/css">
<!--
.align-center {
text-align:center;
}
table {
margin-left: auto;
margin-right: auto;
width: 70%;
}
.block {
width: 50%;
margin-right: auto;
margin-left: auto;
}
.center-div {
width: 70%;
margin-right: auto;
margin-left: auto;
}
.header-text {
font-family: Arial, Helvetica, sans-serif;
font-size: 12pt;
font-weight: bold;
text-align: center;
}
.center-items {
text-align: center;
}
.right-align {
text-align: right;
width: 50%;
}
.left-align {
text-align: left;
width: 50%;
}
#displayDateLast {
text-align: left;
width: 50%;
margin-right: auto;
margin-left: auto;
}
-->
</style>
I'm trying to make a webpage that allows the user to enter from 4 to 6 grades for any course. Next to the letter grade, I'm wanting to put a text-field that accepts the credit hours for the courses. Also when the Calculate GPA button is clicked I want it to verify that a letter grade has been entered and then accumulate the grade points as well as the credit hours and display the GPA. I'm having trouble getting the GPA to calculate though. As well as having an alert display when a user enters anything other than a letter grade? Can someone look over my code and tell me what I should fix or add? Thanks if you read this and attempt to help!
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Chapter 10 Cases and Places: 2</title>
<script type="text/javascript">
<!--Hide from old browsers
function gpacalc() {
var grade = new Array(9);
var credit = new Array(9);
var getGrade = new Array(5);
var getCredit = new Array(5);
var gradeCount = 12;
grade[0] = "A+";
credit[0] = 4;
grade[1] = "A";
credit[1] = 4;
grade[2] = "A-";
credit[2] = 3.7;
grade[3] = "B+";
credit[3] = 3.3;
grade[4] = "B";
credit[4] = 3;
grade[5] = "B-";
credit[5] = 2.7;
grade[6] = "C+";
credit[6] = 2;
grade[7] = "C-";
credit[7] = 1.7;
grade[8] = "D+";
credit[8] = 1.3;
grade[9] = "D";
credit[9] = 1;
grade[10] = "D-";
credit[10] = 0.7;
grade[11] = "F";
credit[11] = 0.0;
getGrade[0] = document.calcGpaForm.grade1.value;
getGrade[0] = getGrade[0].toUpperCase();
getGrade[1] = document.calcGpaForm.grade2.value;
getGrade[1] = getGrade[1].toUpperCase();
getGrade[2] = document.calcGpaForm.grade3.value;
getGrade[2] = getGrade[2].toUpperCase();
getGrade[3] = document.calcGpaForm.grade4.value;
getGrade[3] = getGrade[3].toUpperCase();
getGrade[4] = document.calcGpaForm.grade5.value;
getGrade[4] = getGrade[4].toUpperCase();
getGrade[5] = document.calcGpaForm.grade6.value;
getGrade[5] = getGrade[5].toUpperCase();
getCredit[0] = document.calcGpaForm.credit1.value;
getCredit[1] = document.calcGpaForm.credit2.value;
getCredit[2] = document.calcGpaForm.credit3.value;
getCredit[3] = document.calcGpaForm.credit4.value;
getCredit[4] = document.calcGpaForm.credit5.value;
getCredit[5] = document.calcGpaForm.credit6.value;
var totalGrades =0;
var totalCredits = 0;
var GPA = 0;
var i = 0;
for (i; i < 6; i++) {
if (getGrade[i] == "") {
break;
}
else if (getGrade[i] == "c" || getGrade[i] == "C") {
alert("'C' is not a vaild letter grade. Course " +eval(i + 1)+ ".")
return;
}
else if (isNaN(getCredit[i])) {
alert("Enter a vaild number of credits for Course " +eval(i + 1)+ ".")
return;
}
else if (getCredit[i] == "") {
alert ("You left the number of credits blank for Course " +eval(i + 1)+ ".")
return;
}
var validgradecheck = 0;
var x = 0;
for (x; x < gradeCount; x++) {
if (getGrade[i] == grade[x]) {
totalGrades = totalGrades + (parseInt(getCredit[i],10) * credit[x]);
totalCredits = totalCredits + parseInt(getCredit[i],10);
validgradecheck = 1;
break;
}
}
if (validgradecheck == 0) {
alert("Could not recognize the grade entered for Course " +eval(i + 1)+ ".");
return;
}
}
if (totalCredits == 0) {
alert("Total credits cannot equal zero.");
return;
}
GPA = Math.round(( totalGrades / totalCredits ) * 100) / 100;
alert("GPA = " + eval(GPA));
return;
}
function copyRight() {
var lastModDate = document.lastModified;
var lastModDate = lastModDate.substring(0,10);
displayDateLast.innerHTML = "<h6>Copyright © Hannah. "+" <br /> This document was last modified "+lastModDate+".</h6>";
}
//-->
</script>
<style type="text/css">
<!--
.align-center {
text-align:center;
}
table {
margin-left: auto;
margin-right: auto;
width: 70%;
}
.block {
width: 50%;
margin-right: auto;
margin-left: auto;
}
.center-div {
width: 70%;
margin-right: auto;
margin-left: auto;
}
.header-text {
font-family: Arial, Helvetica, sans-serif;
font-size: 12pt;
font-weight: bold;
text-align: center;
}
.center-items {
text-align: center;
}
.right-align {
text-align: right;
width: 50%;
}
.left-align {
text-align: left;
width: 50%;
}
#displayDateLast {
text-align: left;
width: 50%;
margin-right: auto;
margin-left: auto;
}
-->
</style>
</head>
<body onLoad="gpacalc(); copyRight()">
<div class="center-div">
<p style="font-family:Arial, Helvetica, sans-serif; font-size:xx-large; font-weight:bold; text-align: center; color:blue">Calculating Your GPA</p>
<p class="block"><strong>Directions: </strong>Enter your letter grade for your courses. In the boxes to the right enter the credit hours per course. Then Click the Calculate GPA button to have your GPA calculated as well as your total credit hours.</p>
<form name="calcGpaForm" method="post">
<table>
<tr>
<h4 style="text-align: center">Letter Grade:</h4>
<th class="right-align">
<span style="color:#cc0000;"></span>Course 1:
</th>
<td class="align-left"><input type="text" name="grade1" type="text" id="grade1" size="10" onBlur="validgradecheck" /></td>
<td class="margin-left: auto"><input type="text" name="credit1" id="credit1" size="10" /></td>
</tr>
<tr>
<th class="right-align">
<span style="color:#cc0000;"></span>Course 2:
</th>
<td class="align-left"><input name="grade2" type="text" id="grade2" size="10" onBlur="validgradecheck" /></td>
<td class="align-left"><input type="text" name="credit2" id="credit2" size="10" /></td>
</tr>
<tr>
<th class="right-align">
<span style="color:#cc0000;"></span>Course 3:
</th>
<td class="align-left"><input name="grade3" type="text" id="grade3" size="10" onBlur="validgradecheck" /></td>
<td class="align-left"><input type="text" name="credit3" id="credit3" size="10" /></td>
</tr>
<tr>
<th class="right-align">
<span style="color:#cc0000;"></span>Course 4:
</th>
<td class="align-left"><input name="grade4" type="text" id="grade4" size="10" onBlur="validgradecheck" /> </td>
<td class="align-left"><input type="text" name="credit4" id="credit4" size="10" /></td>
</tr>
<tr>
<th class="right-align">
<span style="color:#cc0000;"></span>Course 5:
</th>
<td class="align-left"><input type="text" name="grade5" id="grade5" size="10" onBlur="validgradecheck" /></td>
<td class="align-left"><input type="text" name="credit5" id="credit5" size="10" /></td>
</tr>
<tr>
<th class="right-align">
<span style="color:#cc0000;"></span>Course 6:
</th>
<td class="align-left"><input type="text" name="grade6" id="grade6" size="10" onBlur="validgradecheck"/></td>
<td class="align-left"><input type="text" name="credit6" id="credit6" size="10" /></td>
</tr>
<tr>
<td class="right-align">
<input name="button" type="button" value="Calculate GPA" onClick="gpacalc()"/>
</td>
<td class="align-left">
<input name="Reset" type="reset" />
</td>
</tr>
<tr>
<td class="right-align">
<span style="font-weight:bolder;">GPA:</span>
</td>
<td><input type="text" name="gpacalc" id="gpacalc" value=" " size="10" /></td>
</tr>
</table>
</form>
</div>
<div id="displayDateLast">
</div>
</body>
</html>
Few remarks:
I don't think you need to worry about old browsers as no one should be using them nowadays. Therefore, <!--Hide from old browsers --> not needed.
What's the point of calculating the GPA when the page loads i.e. onload? There are no grades when the page loads up, so you'll always get an error. It is probably better to only calculate when the user clicks the button.
Do not repeat yourself.
Do not write for yourself to only read but for others, so comment your code.
Check this answer on the difference between dot notation and square brack notation when it comes to accessing an object property.
eval() is evil and not needed in your code.
Here's how I would do it (hopefully it answers all your questions):
// an object is a better data structure for storing grading scale
var gradingScale = {
'A+': 4,
'A': 4,
'A-': 3.7,
'B+': 3.3,
'B': 3,
'B-': 2.7,
'C+': 2.3,
'C-': 1.7,
'D+': 1.3,
'D': 1,
'D-': 0.7,
'F': 0.0
};
// note in JS, you can reference an element by their ID
// attaching onclick event handler to your button with ID "gpacalc"
gpacalc.onclick = function() {
var totalGradePoints = 0;
var totalCredits = 0;
// easier to just start at 1
for (var i = 1; i <= 6; i++) {
// you can access an object's property using [] notation; useful in this situation
// good idea to normalize your values e.g. trim, uppercase, etc
var grade = document.calcGpaForm['grade' + i].value.trim().toUpperCase();
var credit = document.calcGpaForm['credit' + i].value.trim();
// skip if no grade is entered
if (grade == "") {
break;
}
// check if grade is invalid i.e. not in the grading scale
if (!gradingScale.hasOwnProperty(grade)) {
alert("'" + grade + "' is not a valid letter grade. Course " + i + ".");
return;
// check if credit is empty
} else if (credit == "") {
alert("You left the number of credits blank for Course " + i + ".");
return;
// check if credit is not a number
} else if (isNaN(credit)) {
alert("Enter a valid number of credits for Course " + i + ".");
return;
}
// at this point, the grade and credit should both be valid...
credit = parseInt(credit, 10);
// so let's add them to the tally
totalGradePoints += gradingScale[grade] * credit;
totalCredits += credit;
}
// check if total credits is greater than zero
if (totalCredits == 0) {
alert("Total credits cannot equal zero.");
return;
}
// show total
gpa.value = Math.round((totalGradePoints / totalCredits) * 10) / 10;
}
<form name="calcGpaForm" method="post">
<table>
<tr>
<h4 style="text-align: center">Letter Grade:</h4>
<th class="right-align">
<span style="color:#cc0000;"></span>Course 1:
</th>
<td class="align-left"><input type="text" name="grade1" type="text" id="grade1" size="10"></td>
<td class="margin-left: auto"><input type="text" name="credit1" id="credit1" size="10"></td>
</tr>
<tr>
<th class="right-align">
<span style="color:#cc0000;"></span>Course 2:
</th>
<td class="align-left"><input name="grade2" type="text" id="grade2" size="10"></td>
<td class="align-left"><input type="text" name="credit2" id="credit2" size="10"></td>
</tr>
<tr>
<th class="right-align">
<span style="color:#cc0000;"></span>Course 3:
</th>
<td class="align-left"><input name="grade3" type="text" id="grade3" size="10"></td>
<td class="align-left"><input type="text" name="credit3" id="credit3" size="10"></td>
</tr>
<tr>
<th class="right-align">
<span style="color:#cc0000;"></span>Course 4:
</th>
<td class="align-left"><input name="grade4" type="text" id="grade4" size="10"></td>
<td class="align-left"><input type="text" name="credit4" id="credit4" size="10"></td>
</tr>
<tr>
<th class="right-align">
<span style="color:#cc0000;"></span>Course 5:
</th>
<td class="align-left"><input type="text" name="grade5" id="grade5" size="10"></td>
<td class="align-left"><input type="text" name="credit5" id="credit5" size="10"></td>
</tr>
<tr>
<th class="right-align">
<span style="color:#cc0000;"></span>Course 6:
</th>
<td class="align-left"><input type="text" name="grade6" id="grade6" size="10"></td>
<td class="align-left"><input type="text" name="credit6" id="credit6" size="10"></td>
</tr>
<tr>
<td class="right-align">
<input type="button" value="Calculate GPA" id="gpacalc">
</td>
<td class="align-left">
<input name="Reset" type="reset">
</td>
</tr>
<tr>
<td class="right-align">
<span style="font-weight:bolder;">GPA:</span>
</td>
<td><input type="text" id="gpa" value="" size="10"></td>
</tr>
</table>
</form>
(Note: the sample attaches an onclick event handler to your button in the JS and not by using an onclick attribute. Though, the latter way should work.)

how to get the second value from select option in javascript

How do I get the second value of "investortype" and show it within "exploremax"?
<script type="text/javascript">
function $(id) {
return document.getElementById(id);
}
function addCommas(nStr) // adds commas for long numbers in function explore().. eg. 123456 = 123,456
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
function explore() { // this function will calculate how much credits_all and credits_2_all it costs to explore "total". In addition to that I’d also like it to show exploremax.. but it doesn’t work.
var value = document.getElementById(investortype).value;
var split = value.split(":");
var v1 = split[0];
var v2 = split[1];
var toexplore = Number($("toexplore").value);
var total = Number($("total").value);
var exploremax = Math.round(((total * 0.12 * v2) * 1) / 1);
var credit = Math.round(((total * 0.51 * v1) + 700) * Math.pow(10, 10)) / Math.pow(10, 10);
var credit_2 = Math.round(((total * 0.51 * v1) + 850) * Math.pow(10, 10)) / Math.pow(10, 10);
var credit_all = addCommas(Math.round((toexplore * credit) * 1) / 1);
var credit_2_all = addCommas(Math.round((toexplore * credit_2_all) * 1) / 1);
var show_exploremax = addCommas(exploremax);
if ((toexplore == "" || toexplore == null) && (total == "" || total == null)) {
$("credit_all").innerHTML = "Error";
$("credit_2_all").innerHTML = "Error";
$("show_exploremax").innerHTML = "Error";
} else {
$("credit_all").innerHTML = credit_all;
$("credit_2_all").innerHTML = credit_2_all;
$("show_exploremax").innerHTML = show_exploremax;
}
}
</script>
I added the HTML. "show_exploremax" is supposed to read the second value from the "investortype" dropdown menu, but I’m having trouble getting it to do that.
<form action="" id="explore_cost">
<p>
<table width="50%" cellspacing="0px" align="center">
<tbody>
<tr>
<td colspan="2" align="center"><b>Land Explore Cost</b></td>
</tr>
<tr>
<td>Investor type:</td>
<td align="center"><select id="investortype" class="dropdown">
<option value="1:1">Standard</option>
<option value="1.2:0.5">Invasive</option>
<option value="1.1:0.9">Economist</option>
<option value="0.1:9.99">Self-sufficient</option>
<option value="1:1">2nd credit</option>
<option value="1.1:1">Researcher</option>
<!-- I tried to split the values with ":" -->
</select>
</td>
</tr>
<tr>
<td >Amount of Land:</td>
<td align="center"><input id="total" type="text" /></td>
</tr>
<tr>
<td>Land to explore:</td>
<td align="center"><input id="toexplore" type="text" /></td>
</tr>
<tr>
<td>Credit Needed:</td>
<td> <font id="credit_all"></font></td>
</tr>
<tr>
<td>2nd credit Needed:</td>
<td> <font id="credit_2_all"></font></td>
</tr>
<tr>
<td>Explore max:</td>
<td> <font id="show_exploremax"></font></td>
</tr>
<tr><br />
<td align="center" colspan="2"><input type="button" value="Submit" class="button1" onclick="explore()" /></td>
</tr>
</tbody>
EDIT: added html.
document.addEventListener( "DOMContentLoaded", init, false );
function init()
{
var select = document.getElementById('investortype');
select.addEventListener( "change", function() {
var option = select.options[select.selectedIndex];
document.getElementById('show_exploremax').innerText = option.dataset.max;
}, false);
select.selectedIndex = -1;
};
<h4>Pick One</h4>
<select id="investortype" class="dropdown">
<option data-credit="1" data-max="1">Standard</option>
<option data-credit="1.2" data-max="0.5" >Invasive</option>
<option data-credit="1.1" data-max="0.9" >Economist</option>
<option data-credit="0.1" data-max="9.99" value="0.1:9.99">Self-sufficient</option>
<option data-credit="1" data-max="1">2nd credit</option>
<option data-credit="1.1" data-max="1">Researcher</option>
</select>
<h4>2nd option:</h4>
Max: <span id="show_exploremax"></span>

Categories