How to display out put when doing calculations in Javascript? - javascript

I'm trying to calculate two numbers and display them but when I click Calculate Total nothing happens and no numbers are displayed. I've been looking for a solution for hours now and just can't figure out why nothing happens when I click the button. If someone could help me out a little bit I'd be very grateful!
function calcTotal() {
var intValue1 = parseInt(document.GetElementById('Value1').value);
var intValue2 = parseInt(document.GetElementById('Value2').value);
var strOper = document.GetElementById('operators').value;
if (strOper === '+') {
document.GetElementById('Total').value = intValue1 + intValue2;
else if (strOper === '-') {
document.GetElementById('Total').value = intValue1 - intValue2;
} else if (strOper === '*') {
document.GetElementById('Total').value = intValue1 * intValue2;
} else {
document.GetElementById('Total').value = intValue1 / intValue2;
}
}
document.getElementById('submit').onclick = calcTotal();
<table class="table1">
<tr>
<td class="label">
<label id="lblValue1" for="txtValue1">Value 1:</label>
</td>
<td class="control">
<input class="formFields" type="text" id="Value1" name="txtValue1" required>
</td>
</tr>
<tr>
<td>
<select name="dropdown" id="operators">
<option value="+" selected>+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
</td>
</tr>
<tr>
<td class="label">
<label id="lblValue2" for="txtValue2">Value 2:</label>
</td>
<td class="control">
<input class="formFields" type="text" id="Value2" name="txtValue2" required>
</td>
</tr>
</table>
<hr>
<table>
<tr>
<td class="label">
<label id="lblTotal" for="txtTotal">Total:</label>
</td>
<td class="control">
<input class="textview" type="text" id="Total" name="txtTotal">
</td>
</tr>
</table>
<table>
<tr>
<td class="label">
<input id="submit" class="button" name='cmdCalcTotal' type="button" value="Calculate Total" onclick="calcTotal();">
</td>
</tr>
</table>
Thanks in advance!!!!

Your logic behind this code is actually working just fine. You just had a few syntax errors.
There was no closing brackets (}) for the if statement.
Also, you had .GetElementById(). You should've had .getElementById() (the g is supposed to be lowercase).
Also, you don't need to have a .onclick event in the javascript, if you already have on in the html. I removed that for you.
It's fixed in the snippet for you.
function calcTotal() {
var intValue1 = parseInt(document.getElementById('Value1').value);
var intValue2 = parseInt(document.getElementById('Value2').value);
var strOper = document.getElementById('operators').value;
if (strOper === '+') {
document.getElementById('Total').value = intValue1 + intValue2;
} else if (strOper === '-') {
document.getElementById('Total').value = intValue1 - intValue2;
} else if (strOper === '*') {
document.getElementById('Total').value = intValue1 * intValue2;
} else {
document.getElementById('Total').value = intValue1 / intValue2;
}
}
<table class="table1">
<tr>
<td class="label">
<label id="lblValue1" for="txtValue1">Value 1:</label>
</td>
<td class="control">
<input class="formFields" type="text" id="Value1" name="txtValue1" required>
</td>
</tr>
<tr>
<td>
<select name="dropdown" id="operators">
<option value="+" selected>+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
</td>
</tr>
<tr>
<td class="label">
<label id="lblValue2" for="txtValue2">Value 2:</label>
</td>
<td class="control">
<input class="formFields" type="text" id="Value2" name="txtValue2" required>
</td>
</tr>
</table>
<hr>
<table>
<tr>
<td class="label">
<label id="lblTotal" for="txtTotal">Total:</label>
</td>
<td class="control">
<input class="textview" type="text" id="Total" name="txtTotal">
</td>
</tr>
</table>
<table>
<tr>
<td class="label">
<input id="submit" class="button" name='cmdCalcTotal' type="button" value="Calculate Total" onclick="calcTotal();">
</td>
</tr>
</table>

There are some error in your code:
Missing {} for if block
Uppercase GetElementById method, note that all function with uppercase are difference, also with css and Id and class.
Redundant //document.getElementById('submit').onclick = calcTotal();
If you want keep last line you can edit to
document.getElementById('submit').addEventListener("click", calcTotal);
and remove onclick="calcTotal();" on button
function calcTotal() {
var intValue1 = parseInt(document.getElementById('Value1').value);
var intValue2 = parseInt(document.getElementById('Value2').value);
var strOper = document.getElementById('operators').value;
if (strOper === '+') {
document.getElementById('Total').value = intValue1 + intValue2;
}
else if (strOper === '-') {
document.getElementById('Total').value = intValue1 - intValue2;
} else if (strOper === '*') {
document.getElementById('Total').value = intValue1 * intValue2;
} else {
document.getElementById('Total').value = intValue1 / intValue2;
}
}
document.getElementById('submit').addEventListener("click", calcTotal);
<table class="table1">
<tr>
<td class="label">
<label id="lblValue1" for="txtValue1">Value 1:</label>
</td>
<td class="control">
<input class="formFields" type="text" id="Value1" name="txtValue1" required>
</td>
</tr>
<tr>
<td>
<select name="dropdown" id="operators">
<option value="+" selected>+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
</td>
</tr>
<tr>
<td class="label">
<label id="lblValue2" for="txtValue2">Value 2:</label>
</td>
<td class="control">
<input class="formFields" type="text" id="Value2" name="txtValue2" required>
</td>
</tr>
</table>
<hr>
<table>
<tr>
<td class="label">
<label id="lblTotal" for="txtTotal">Total:</label>
</td>
<td class="control">
<input class="textview" type="text" id="Total" name="txtTotal">
</td>
</tr>
</table>
<table>
<tr>
<td class="label">
<input id="submit" class="button" name='cmdCalcTotal' type="button" value="Calculate Total" >
</td>
</tr>
</table>

Related

How can I sum elements in a html table after filtering by class?

I created the following table by defining different classes in javascript (the table is actually bigger but I reduced it to 3 lines for a better comprehension).
I type manually the inputs in the first column and it calculates A, B, C and SUM.
A = 5 * input
B = 4 * input
C = 3 * input
SUM = A + B + C
Total SUM =should be in this example 36 + 24 + 60 (actually there are more rows in my column) but I don't know exactly how to automatize the job. I am trying something in this direction but it does not do the job:
forEach ({
row.querySelector(".total").value +- = (Number(row.querySelector(".sum"))
Here is the code of the table and how I generate the values:
<table class="egt" bgcolor="Olive">
<! --SEGUNDA LINEA -->
<thead>
<tr>
<th>INPUT</th>
<th>A</th>
<th>B</th>
<th>C</th>
<th>SUM</th>
</tr>
</thead>
<! --TERCERA LINEA -->
<tr>
<td>
<input type="number" class="fuel" style="text-align:center">
</td>
<td>
<input class="A" type="number" style="text-align:center" />
</td>
<td>
<input class="B" type="number" style="text-align:center" />
</td>
<td>
<input class="C" type="number" style="text-align:center" />
</td>
<td>
<input class="sum" type="number" style="text-align:center" />
</td>
</tr>
<tr>
<td>
<input type="number" class="fuel" style="text-align:center">
</td>
<td>
<input class="A" type="number" style="text-align:center" />
</td>
<td>
<input class="B" type="number" style="text-align:center" />
</td>
<td>
<input class="C" type="number" style="text-align:center" />
</td>
<td>
<input class="sum" type="number" style="text-align:center" />
</td>
</tr>
<tr>
<td>
<input type="number" class="fuel" style="text-align:center">
</td>
<td>
<input class="A" type="number" style="text-align:center" />
</td>
<td>
<input class="B" type="number" style="text-align:center" />
</td>
<td>
<input class="C" type="number" style="text-align:center" />
</td>
<td>
<input class="sum" type="number" style="text-align:center" />
</td>
</tr>
<! --ULTIMA LINEA -->
<tr>
<th colspan="4" align="right">Total SUM = </th>
<td><input class="total" type="number" /></td>
</tr>
</table>
let rows = document.querySelectorAll("tbody tr");
[...rows].forEach(row => {
row.querySelector(".fuel").addEventListener("input", (event) => {
calculate(row)
})
})
function calculate(row) {
let fuel = row.querySelector(".fuel").value;
row.querySelector(".A").value = (5 * fuel);
row.querySelector(".B").value = (4 * fuel);
row.querySelector(".C").value = (3 * fuel);
row.querySelector(".sum").value = (Number(row.querySelector(".A").value) + Number(row.querySelector(".B").value) + Number(row.querySelector(".C").value));
}
Thanks for your advise!
I tried to simplify your example a bit. Selected all the elements we're going to need at the start of the code and then attached the event listener to your inputs. When input value changes, we're recalculating the sum of the entire row and the total sum afterwards.
const totalSum = document.querySelector('.total');
const inputs = document.querySelectorAll('.fuel');
const sums = document.querySelectorAll('.sum');
inputs.forEach(input => {
input.addEventListener('input', event => {
recalculateRowSum(input);
recalculateTotalSum();
});
});
function recalculateRowSum(input) {
const row = input.parentNode.parentNode;
const a = input.value * 5;
const b = input.value * 4;
const c = input.value * 3;
const sum = a + b + c;
row.querySelector('.A').value = a;
row.querySelector('.B').value = b;
row.querySelector('.C').value = c;
row.querySelector('.sum').value = sum;
}
function recalculateTotalSum() {
totalSum.value = [...sums].reduce((total, current) => total += +current.value, 0);
}
<table class="egt" bgcolor="Olive">
<! --SEGUNDA LINEA -->
<thead>
<tr>
<th>INPUT</th>
<th>A</th>
<th>B</th>
<th>C</th>
<th>SUM</th>
</tr>
</thead>
<! --TERCERA LINEA -->
<tbody>
<tr>
<td>
<input type="number" class="fuel" style="text-align:center">
</td>
<td>
<input class="A" type="number" style="text-align:center" />
</td>
<td>
<input class="B" type="number" style="text-align:center" />
</td>
<td>
<input class="C" type="number" style="text-align:center" />
</td>
<td>
<input class="sum" type="number" style="text-align:center" />
</td>
</tr>
<tr>
<td>
<input type="number" class="fuel" style="text-align:center">
</td>
<td>
<input class="A" type="number" style="text-align:center" />
</td>
<td>
<input class="B" type="number" style="text-align:center" />
</td>
<td>
<input class="C" type="number" style="text-align:center" />
</td>
<td>
<input class="sum" type="number" style="text-align:center" />
</td>
</tr>
<tr>
<td>
<input type="number" class="fuel" style="text-align:center">
</td>
<td>
<input class="A" type="number" style="text-align:center" />
</td>
<td>
<input class="B" type="number" style="text-align:center" />
</td>
<td>
<input class="C" type="number" style="text-align:center" />
</td>
<td>
<input class="sum" type="number" style="text-align:center" />
</td>
</tr>
<! --ULTIMA LINEA -->
<tr>
<th colspan="4" align="right">Total SUM = </th>
<td><input class="total" type="number" /></td>
</tr>
</tbody>
</table>
add new function to update total value
let rows = document.querySelectorAll("tbody tr");
[...rows].forEach(row => {
row.querySelector(".fuel").addEventListener("input", (event) => {
calculate(row)
})
})
function calculate(row) {
let fuel = row.querySelector(".fuel").value;
row.querySelector(".A").value = (5 * fuel);
row.querySelector(".B").value = (4 * fuel);
row.querySelector(".C").value = (3 * fuel);
row.querySelector(".sum").value = (Number(row.querySelector(".A").value) + Number(row.querySelector(".B").value) + Number(row.querySelector(".C").value));
calculateSum();
}
function calculateSum() {
let elements = document.querySelectorAll("tbody .sum");
let total = 0;
[...elements].forEach(ele => {
total += parseFloat(ele.value) || 0;
})
document.querySelector("tbody .total").value = total;
}
Let's clean it up:
const setup = () => {
const rows = document.querySelectorAll('.fuel');
[...rows].forEach(row => row.addEventListener('input', onInput));
}
const calculateSum = () => {
const sums = [...document.querySelectorAll('.sum')].map(input => Number.parseInt(input.value));
const result = sums.reduce((sum, value) => sum + value);
document.querySelector('.total').value = result;
}
const onInput = event => {
const input = event.target;
const currentIndex = input.dataset.rowIndex;
const fuel = Number.parseInt(input.value, 10);
const [A, B, C] = [(5 * fuel), (4 * fuel), (3 * fuel)]
const sum = A + B + C;
document.querySelector(`[data-row-index="${currentIndex}"].A`).value = A;
document.querySelector(`[data-row-index="${currentIndex}"].B`).value = B;
document.querySelector(`[data-row-index="${currentIndex}"].C`).value = C;
document.querySelector(`[data-row-index="${currentIndex}"].sum`).value = sum;
calculateSum();
}
//load
window.addEventListener('load', setup);
tbody input[type="number"] {
text-align: center;
}
<table class="egt" bgcolor="Olive">
<thead>
<tr>
<th>INPUT</th>
<th>A</th>
<th>B</th>
<th>C</th>
<th>SUM</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input class="fuel" data-row-index="0" type="number">
</td>
<td>
<input class="A" data-row-index="0" type="number" disabled>
</td>
<td>
<input class="B" data-row-index="0" type="number" disabled>
</td>
<td>
<input class="C" data-row-index="0" type="number" disabled>
</td>
<td>
<input class="sum" data-row-index="0" type="number" disabled>
</td>
</tr>
<tr>
<td>
<input class="fuel" data-row-index="1" type="number">
</td>
<td>
<input class="A" data-row-index="1" type="number" disabled>
</td>
<td>
<input class="B" data-row-index="1" type="number" disabled>
</td>
<td>
<input class="C" data-row-index="1" type="number" disabled>
</td>
<td>
<input class="sum" data-row-index="1" type="number" disabled>
</td>
</tr>
<tr>
<td>
<input class="fuel" data-row-index="2" type="number">
</td>
<td>
<input class="A" data-row-index="2" type="number" disabled>
</td>
<td>
<input class="B" data-row-index="2" type="number" disabled>
</td>
<td>
<input class="C" data-row-index="2" type="number" disabled>
</td>
<td>
<input class="sum" data-row-index="2" type="number" disabled>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<th colspan="4" align="right">Total SUM = </th>
<td><input class="total" type="number" disabled></td>
</tr>
</tfoot>
</table>

Return false statement not working for my form

I have a form and i am validating it by checking if there is no empty field left by putting an alert and returning false so that it remains on the same page and doesn't go to the next page. Although i am getting the alert but still it proceeds to next page.
function fnOnSubmit() {
$('#dataTable input,select').each(function() {
var id = $(this).attr('id');
var val = $(this).val();
if (val == '' || val == 'undefined') {
alert('Please fill all the fields');
return false;
}
});
var flag = '';
$('#dataTable input:not([type=button]),#dataTable select').each(function () {
flag = flag + (this.value) + '~';
quicklink = flag;
});
document.frmmain.quicklink.value = quicklink;
SendTxnRequest('02','QWC');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="0" cellspacing="1" cellpadding="1" id="dataTable" name="dataTable" class="graphtable">
<thead>
<tr>
<td class="headingalign" width="16%">Links</td>
<td class="headingalign" width="32%">Desciption</td>
<td class="headingalign" width="16%">Image</td>
<td class="headingalign" width="16%">URL</td>
<td class="headingalign" width="05%"></td>
</tr>
</thead>
<tbody>
<tr id="id0" class="vals" name="id0">
<td>
<div class="id_100">
<select type="select-one" id='fldsearch' class="objselect" name="fldsearch" onChange="disableField(this)">
<option value="">Select</option>
<xsl:for-each select="faml/response/qlwidgetresponsedto/searchby/datamapdto">
<xsl:sort order="ascending" select="description" />
<option value="#{description}">
<xsl:value-of select="description" />
</option>
</xsl:for-each>
</select>
</div>
</td>
<td>
<input id="flddesc" name="flddesc" maxlength="500" disabled="true" class="objinputtext1" size="85" value="" />
</td>
<td>
<input id="fldimg" name="fldimg" maxlength="50" disabled="true" class="objinputtext2" size="45" value="" />
</td>
<td>
<input id="fldurl" name="fldurl" maxlength="55" disabled="true" class="objinputtext3" size="40" value="" />
</td>
<td>
<input tabindex="6" value="Delete Row" disabled="true" class="DeleteButton" type="button" />
</td>
</tr>
</tbody>
</table>

Javascript validation for my report page

I have a table where I generate reports. I need to write javascript validation for this one report. Unfortunately, my javascript is very weak. I have the server side validation in place, but I also need to have javascript validation. My page is as follows...
<tr>
<form name="MedicaidResidents" action="Medicaid_Residents.cfm" method="post" id='f1' onSubmit="ValidateForm(this.form);">
<td nowrap="nowrap">
Medicaid Residents
</td>
<td style="width: 5%;">
<table style="width: 5%;">
<tr>
<td style="width: 5%;"><br><br>
<input type="radio" name="choice" value='1' onClick="check_radio()";>All<br><br>
<input type="radio" name="choice" value='2' onClick="check_radio()";>States<br><br>
<input type="radio" name="choice" value='3' onClick="check_radio()";>Communities
</td>
<td style="width: 5%;">
<select name="stateprompt1" multiple="multiple" size="10" id="T1">
<cfloop query="Medicaid_States">
<option value="#Medicaid_States.State_Code#">#Medicaid_States.State_Code#</option>
</cfloop>
</select>
</td>
<td style="width: 10%;">
<select name="houseprompt1" multiple="multiple" size="10" id="T2">
<cfloop query="Medicaid_Houses">
<option value="#Medicaid_Houses.iHouse_ID#">#Medicaid_Houses.Community# </option>
</cfloop>
</select>
</td>
</tr>
</table>
</td>
<td>
<table style="width: 5%;">
<tr>
<td>
From
</td>
</tr>
<tr>
<td>
<input type="text" id="txtFromDate" name="dateprompt1">
</td>
</tr>
<tr>
<td>
</td>
</tr>
<tr>
<td>
To
</td>
</tr>
<tr>
<td>
<input type="text" id="txtToDate" name="dateprompt2">
</td>
</tr>
</table>
</td>
<td>
<input type="Submit" name="Go" value="GO" style="font-size: 12; color: navy; height: 20px; width: 60px;">
</td>
</form>
</tr>
The javascript I wrote is...
<script LANGUAGE="JavaScript">
function ValidateForm(form){
if ( ( form.choice[0].checked == false ) && ( form.choice[1].checked == false ) && ( form.choice[2].checked == false ) )
{
alert ( "Please first select a radiobutton" );
return false;
}
elseif ( ( form.choice[1].checked == True ) && ( document.getElementById("T1").value==""))
{
alert ( "Please select a State" );
return false;
}
elseif ( ( form.choice[2].checked == True ) && ( document.getElementById("T2").value==""))
{
alert ( "Please select a House" );
return false;
}
elseif ( ( document.dateprompt1.value =="") && ( document.dateprompt2.value==""))
{
alert ( "please select 'From' and 'To' dates" );
return false;
}
}
</script>
...but it doesn't work. I know the javascript is poorly writen. I would appreciate any help in getting it to work!
Rather than have a series of else statements just have the if statements because they will stop it with the return false, and the green/passed path/action is at the bottom.
function ValidateForm(){
var a = document.forms["MedicaidResidents"]["choice"].value;
var b = document.forms["MedicaidResidents"]["stateprompt1"].value;
var c = document.forms["MedicaidResidents"]["houseprompt1"].value;
var d = document.forms["MedicaidResidents"]["dateprompt1"].value;
var e = document.forms["MedicaidResidents"]["dateprompt2"].value;
if (a == null || a == "") {
alert("Please first select a radiobutton");
return false;
}
if (b == null || b == "") {
alert("Please select a State");
return false;
}
if (c == null || c == "") {
alert("Please select a House");
return false;
}
if (d == null || d == "" && e == null || e == "") {
alert("please select 'From' and 'To' dates");
return false;
}
return true;
}
<tr>
<form name="MedicaidResidents" action="Medicaid_Residents.cfm" method="post" id='f1' onSubmit="return ValidateForm();">
<td nowrap="nowrap">
Medicaid Residents
</td>
<td style="width: 5%;">
<table style="width: 5%;">
<tr>
<td style="width: 5%;"><br><br>
<input type="radio" name="choice" value='1' onClick="check_radio()">All<br><br>
<input type="radio" name="choice" value='2' onClick="check_radio()">States<br><br>
<input type="radio" name="choice" value='3' onClick="check_radio()">Communities
</td>
<td style="width: 5%;">
<select name="stateprompt1" multiple="multiple" size="10" id="T1">
<cfloop query="Medicaid_States">
<option value="#Medicaid_States.State_Code#">#Medicaid_States.State_Code#</option>
</cfloop>
</select>
</td>
<td style="width: 10%;">
<select name="houseprompt1" multiple="multiple" size="10" id="T2">
<cfloop query="Medicaid_Houses">
<option value="#Medicaid_Houses.iHouse_ID#">#Medicaid_Houses.Community# </option>
</cfloop>
</select>
</td>
</tr>
</table>
</td>
<td>
<table style="width: 5%;">
<tr>
<td>
From
</td>
</tr>
<tr>
<td>
<input type="text" id="txtFromDate" name="dateprompt1">
</td>
</tr>
<tr>
<td>
</td>
</tr>
<tr>
<td>
To
</td>
</tr>
<tr>
<td>
<input type="text" id="txtToDate" name="dateprompt2">
</td>
</tr>
</table>
</td>
<td>
<input type="Submit" name="Go" value="GO" style="font-size: 12; color: navy; height: 20px; width: 60px;">
</td>
</form>
</tr>
https://jsbin.com/kawewerisu/1/edit?html,js,output

Get mondays dates based on selected month in javascript

This question is related to this SO question, and the provided solution is working fine. However, in my case, I want to get dates of mondays in a selected month from dropdown menu.
The code what I have tried is:
var d = new Date(),
month = d.getMonth(),
mondays = [],
mondaysChange = [];
//console.log("current month is: "+month);
//console.log("current months mondays are: " + getMondays());
$("#ddlMonths option").filter(function() {
return this.value == month;
}).attr('selected', true);
$('#ddlMonths').on('change', function(e) {
var m = $("option:selected", this).val();
console.log("selected month: " + m);
var str = getMondaysChange(m);
console.log("selected months mondays are: " + str);
});
function getMondaysChange(m) {
d.setDate(1);
d.setMonth(m);
console.log("you have selected: " + d + " month");
while (d.getDay() !== 1) {
d.setDate(d.getDate() + 1);
}
// Get all the other Mondays in the month
while (d.getMonth() === m) {
mondaysChange.push(new Date(d.getTime()));
d.setDate(d.getDate() + 7);
}
return mondaysChange;
}
function getMondays() {
d.setDate(1);
while (d.getDay() !== 1) {
d.setDate(d.getDate() + 1);
}
// Get all the other Mondays in the month
while (d.getMonth() === month) {
mondays.push(new Date(d.getTime()));
d.setDate(d.getDate() + 7);
}
return mondays;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment-with-locales.min.js"></script>
<div class="data-block">
<div class="data-container">
<header>
<h2>
Track</h2>
</header>
<div class="form-horizontal">
<div class="form-group">
<label for="CAASRTUserName" class="col-sm-2 control-label">Resource</label>
<div class="col-sm-10">
<input id="CAASRTUserName" type="text" data-bind="value: Vendor" placeholder="" class="form-control hasclear">
</div>
</div>
<div class="form-group has-feedback">
<label for="InvoiceTotal" class="col-sm-2 control-label">Enter for Month</label>
<div class="col-sm-10">
<select id="ddlMonths" class="form-control">
<option value="0">January</option>
<option value="1">February</option>
<option value="2">March</option>
<option value="3">April</option>
<option value="4">May</option>
<option value="5">June</option>
<option value="6">July</option>
<option value="7">August</option>
<option value="8">September</option>
<option value="9">October</option>
<option value="10">November</option>
<option value="11">December</option>
</select>
</div>
</div>
<!-- <div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button id="btnTrack" data-bind="click: Submit" class="btn btn-default">
Submit
</button>
</div>
</div> --></div>
<br>
<div class="row">
<div class="col-md-12">
<!-- <h4>
<span id="mySpanCur">Current Week</span>
</h4> -->
<div id="divtblTrack" class="plan">
<table id="tblTrack" class="table table-bordered">
<thead>
<tr>
<th>Parent Activity</th>
<th>Hrs/ Wk</th>
<th>Activity</th>
<th><span id="week1"></span>
</th>
<th><span id="week2"></span>
</th>
<th><span id="week3"></span>
</th>
<th><span id="week4"></span>
</th>
<th>Comments</th>
<th>Total</th>
<th style="display:none">PlanEntryId</th>
</tr>
</thead>
<tfoot>
<tr>
<td></td>
<td id="HrsByWkSum">204</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td id="TotalSum">0</td>
<td style="display:none"></td>
</tr>
</tfoot>
<tbody>
<tr>
<td class="emptyTd"><span>Analytics</span>
</td>
<td class="hoursbyweek emptyTd"><span>67</span>
</td>
<td class="DD">
<select class="form-control" readonly="readonly">
<option value="Select">Select</option>
</select>
</td>
<td class="mon">
<input type="text" id="txtMon" class="form-control" style="width:40px;" value="" />
</td>
<td class="tue">
<input type="text" id="txtTue" class="form-control" style="width:40px;" value="" />
</td>
<td class="wed">
<input type="text" id="txtWed" class="form-control" style="width:40px;" value="" />
</td>
<td class="thu">
<input type="text" id="txtThu" class="form-control" style="width:40px;" value="">
</td>
<td>
<input type="text" id="txtComments" class="form-control" style="width:90px;" value="">
</td>
<td class="tot emptyTdTot"></td>
<td style="display:none">3</td>
<td>
<button class="btn btn-primary btn-xs myBtn">Add</button>
</td>
</tr>
<tr>
<td class="emptyTd"><span>General Admin</span>
</td>
<td class="hoursbyweek emptyTd"><span>36</span>
</td>
<td class="DD">
<select class="form-control" readonly="readonly">
<option value="Select">Select</option>
</select>
</td>
<td class="mon">
<input type="text" id="txtMon" class="form-control" style="width:40px;" value="">
</td>
<td class="tue">
<input type="text" id="txtTue" class="form-control" style="width:40px;" value="">
</td>
<td class="wed">
<input type="text" id="txtWed" class="form-control" style="width:40px;" value="">
</td>
<td class="thu">
<input type="text" id="txtThu" class="form-control" style="width:40px;" value="">
</td>
<td>
<input type="text" id="txtComments" class="form-control" style="width:90px;" value="">
</td>
<td class="tot emptyTdTot"></td>
<td style="display:none">2</td>
<td>
<button class="btn btn-primary btn-xs myBtn">Add</button>
</td>
</tr>
<tr>
<td class="emptyTd"><span>Reports</span>
</td>
<td class="hoursbyweek emptyTd"><span>56</span>
</td>
<td class="DD">
<select class="form-control" readonly="readonly">
<option value="Select">Select</option>
</select>
</td>
<td class="mon">
<input type="text" id="txtMon" class="form-control" style="width:40px;" value="">
</td>
<td class="tue">
<input type="text" id="txtTue" class="form-control" style="width:40px;" value="">
</td>
<td class="wed">
<input type="text" id="txtWed" class="form-control" style="width:40px;" value="">
</td>
<td class="thu">
<input type="text" id="txtThu" class="form-control" style="width:40px;" value="">
</td>
<td>
<input type="text" id="txtComments" class="form-control" style="width:90px;" value="">
</td>
<td class="tot emptyTdTot"></td>
<td style="display:none">6</td>
<td>
<button class="btn btn-primary btn-xs myBtn">Add</button>
</td>
</tr>
<tr>
<td class="emptyTd"><span>Time not working</span>
</td>
<td class="hoursbyweek emptyTd"><span>45</span>
</td>
<td class="DD">
<select class="form-control" readonly="readonly">
<option value="Select">Select</option>
</select>
</td>
<td class="mon">
<input type="text" id="txtMon" class="form-control" style="width:40px;" value="">
</td>
<td class="tue">
<input type="text" id="txtTue" class="form-control" style="width:40px;" value="">
</td>
<td class="wed">
<input type="text" id="txtWed" class="form-control" style="width:40px;" value="">
</td>
<td class="thu">
<input type="text" id="txtThu" class="form-control" style="width:40px;" value="">
</td>
<td>
<input type="text" id="txtComments" class="form-control" style="width:90px;" value="">
</td>
<td class="tot emptyTdTot"></td>
<td style="display:none">1</td>
<td>
<button class="btn btn-primary btn-xs myBtn">Add</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<div class="pull-right">
<button id="btnSubmit" data-bind="click: Submit" class="btn btn-default">Save</button>
</div>
</div>
</div>
</div>
<br>
</div>
</div>
Jsbin for the same is here. I am setting the month on change of dropdown and am still wondering why the mondaysChange array is returning empty. Can anyone check it?
A momentjs solution for the same also fine which I can't seem to get it easily.
for start of week use this
var startDay = 0;
var d =today.getDay();
var weekStart = new Date(today.valueOf() - (d<=0 ? 7-startDay:d-startDay)*86400000); //rewind to start day
var nextweekStart =new Date(weekStart.valueOf() + (7)*86400000);//get first day of next week
var prevweekStart =new Date(weekStart.valueOf() - (7)*86400000);//get first day of prev week
if startDay =0; return sunday then use 1 instead of 0 as:
//0=sunday, 1=monday etc.
Here's a more generic function to retrieve all dates for a certain day for a month from a given date. See the snippet, where it is used within the change handler of the selector.
function getAllInstancesOfDayInMonth(fordate, forday) {
fordate.setDate(1);
var start = getStartDay(fordate, forday)
,month = fordate.getMonth()
,result = [start];
while (fordate.getMonth() == month) {
result.push(new Date(fordate.setDate(fordate.getDate()+7)));
}
return result.slice(0,-1);
function getStartDay(d, forday) {
return d.getDay() != +forday
? ( d.setDate( d.getDate() + 1 ), getStartDay(d, forday) )
: new Date(d);
}
}
(function () {
document.querySelector('#ddlMonths')
.addEventListener('change', getMondays);
var result = document.querySelector('#result');
result.innerHTML = '<h3>all mondays in January 2015</h3>';
result.innerHTML += getAllInstancesOfDayInMonth(
new Date([2015,1,1].join('/')), 1
).join('\n');
function getMondays(e){
var year = this.getAttribute('data-year')
,month = +this.options[this.selectedIndex].value
,monthstr = this.options[this.selectedIndex].innerHTML;
result.innerHTML = '<h3>all mondays in '+monthstr+' '+ year+'</h3>';
result.innerHTML += getAllInstancesOfDayInMonth(
new Date([year,month+1,1].join('/')), 1
).join('\n');
}
function getAllInstancesOfDayInMonth(fordate, forday) {
fordate.setDate(1);
var start = getStartDay(fordate, forday)
,month = fordate.getMonth()
,result = [start];
while (fordate.getMonth() == month) {
result.push(new Date(fordate.setDate(fordate.getDate()+7)));
}
return result.slice(0,-1);
function getStartDay(d, forday) {
return d.getDay() != +forday
? ( d.setDate( d.getDate() + 1 ), getStartDay(d, forday) )
: new Date(d);
}
}
}())
body {font: 12px/15px normal verdana, arial; margin:1.5em; }
<select id="ddlMonths" class="form-control" data-year="2015">
<option value="0">January</option>
<option value="1">February</option>
<option value="2">March</option>
<option value="3">April</option>
<option value="4">May</option>
<option value="5">June</option>
<option value="6">July</option>
<option value="7">August</option>
<option value="8">September</option>
<option value="9">October</option>
<option value="10">November</option>
<option value="11">December</option>
</select> Select a month to retrieve all mondays of it
<pre id="result"></pre>
I think the problem is the comparison d.getMonth() === m, you are passing m as the selected option value which will be of type string where as d.getMonth() is a of type number.
so try
//empty the array
mondaysChange.length = 0;
//change the type of m to number
m = +m;
d.setDate(1);
d.setMonth(m);
console.log("you have selected: " + d + " month");
while (d.getDay() !== 1) {
d.setDate(d.getDate() + 1);
}
// Get all the other Mondays in the month
while (d.getMonth() === m) {
mondaysChange.push(new Date(d.getTime()));
d.setDate(d.getDate() + 7);
}
Demo: Fiddle, Problem

calculation of total price from order form in either jquery or javascript

I have tried to make a order form and get it checked by jQuery as well as calculating the prices. everything works fine. I have it so when the user puts in a zero again (= he doesn't want the item anymore) it recalculates this function also makes sure no 00001 orders go trough.
Now the problem is my total price. I haven't been able to create the correct loop for the job. I hope some of you can guide me in the right direction.
The site is located here: caferene
function productprijs(prijs, myfield, targetfield) {
prijs = prijs.replace(",", ".");
aantal = myfield.value;
//
if (aantal != "") {
//kijken als het eerste cijfer een 0 is
if (aantal.substr(0, 1) == "0") {
//als lengte = 1 is gewoon veranderen in een 1, anders de 0 weglaten
if (aantal.length == 1) {
aantal = "0";
} else {
aantal = aantal.substr(1, (aantal.length - 1));
}
myfield.value = aantal;
}
//
subtotaal = parseFloat(prijs) * parseInt(aantal);
subtotaal = Math.round(subtotaal * 100) / 100;
subtotaal = subtotaal.toString();
posPunt = subtotaal.lastIndexOf(".");
//
if (posPunt == -1) {
subtotaal = subtotaal + ".00";
} else {
naPunt = subtotaal.substr(posPunt + 1, (subtotaal.length - 1));
if (naPunt.length == 1) {
subtotaal = subtotaal + "0";
}
}
subtotaal = subtotaal.replace(".", ",");
//
document.getElementById(targetfield).innerHTML = subtotaal;
//
}
myFunction;
}
function myFunction() {
totaalPrijs = 0;
aantalProd = parseInt(document.getElementById("aantalProducten").value);
for (var i = -1; i < aantalProd; i++) {
subPrijs = document.getElementById("subtotaal1").innerHTML;
if (subPrijs != "") {
totaalPrijs += parseFloat(subPrijs.replace(",", "."));
alert("€" + totaalPrijs);
}
}
}
function numbersonly(myfield, e) {
var key;
var keychar;
if (window.event) {
key = window.event.keyCode;
} else if (e) {
key = e.which;
} else {
return true;
}
keychar = String.fromCharCode(key);
// pijltjes, backspace, tab, mogen wel ingedrukt worden
if ((key == null) || (key == 0) || (key == 8) || (key == 9) || (key == 13) || (key == 27)) {
return true;
} else if ((("0123456789").indexOf(keychar) > -1)) {
return true;
} else {
return false;
}
}
function checkProdForm(myForm) {
//
var bIsValid = true;
//
// datum
if (document.getElementById("afhaling_datum").value == "dd/mm/yyyy" || document.getElementById("afhaling_datum").value == "") {
bIsValid = false;
document.getElementById("resp").innerHTML = "Gelieve een correcte datum in te vullen";
document.getElementById("resp").style.display = "block";
}
if (document.getElementById("totaal").innerHTML == "0,00") {
bIsValid = false;
document.getElementById("resp").innerHTML = "Gelieve minstens 1 product te selecteren";
document.getElementById("resp").style.display = "block";
}
//
if (bIsValid) {
document.getElementById("resp").innerHTML = "";
document.getElementById("resp").style.display = "none";
}
//
return bIsValid;
//
}
body {
padding-top: 120px;
padding-left: 20%;
width: 80%;
}
.titel {
background-color: #408CAE;
}
#rij1 {
background-color: #D7EFFA
}
#rij2 {
background-color: #F2F4F5
}
.bedrag .aantal. {
width: 4%;
}
.prijs {
width: 9%;
}
.opties {
width: 9%;
}
.titelbeschrijving {
width: 60%;
}
.comments {
width: 170px;
height: 180px;
border: 1px solid #999999;
padding: 5px;
}
.gegevens td {
padding: 3px;
}
<section id="bestellen" class="bestellen">
<form form action="bestellen.php" method="GET" onsubmit="return checkProdForm(this)">
<table cellpadding="0" cellspacing="0" border="0" id="prodtabel">
<tbody id="tabel">
<tr class="titel" id="oesters">
<td class="titelbeschrijving">Oesters</td>
<td class="opties">opties</td>
<td class="prijs">prijs</td>
<td class="aantal">aantal</td>
<td class="bedrag">bedrag</td>
</tr>
<tr class="prod0" id="rij1">
<td class="beschrijving">speciales Gillardeau</td>
<td>
<select name="extra0" id="extra0">
<option selected="selcted" value="gekraakt">gekraakt</option>
<option value="niet-gekraakt">niet-gekraakt</option>
</select>
</td>
<td>€3/stuk</td>
<td>
<input type="text" name="art0" id="art0" onkeypress="return numbersonly(this, event)" onkeyup="productprijs('3', this, 'subtotaal0')" style="width:50px">
</td>
<td id='subtotaal0'>0,00</td>
</tr>
<tr class="prod1" id="rij2">
<td class="beschrijving">Oosterschelde Creuses</td>
<td>
<select name="extra1" id="extra0">
<option value="gekraakt">gekraakt</option>
<option value="niet-gekraakt">niet-gekraakt</option>
</select>
<td>€2/stuk</td>
<td>
<input type="text" name="art1" id="art0" onkeypress="return numbersonly(this, event)" onkeyup="productprijs('2', this, 'subtotaal1')" style="width:50px">
</td>
<td id='subtotaal1'>0,00</td>
</tr>
<tr class="prod2" id="rij1">
<td class="beschrijving">Zeeuwse platte oesters</td>
<td>
<select name="extra2" id="extra0">
<option value="gekraakt">gekraakt</option>
<option value="niet-gekraakt">niet-gekraakt</option>
</select>
</td>
<td>€3/stuk</td>
<td>
<input type="text" name="art2" id="art0" onkeypress="return numbersonly(this, event)" onkeyup="productprijs('3', this, 'subtotaal2')" style="width:50px">
</td>
<td id='subtotaal2'>0,00</td>
</tr>
<tr class="prod3 id=" rij2 "">
<td class="beschrijving">Ierlands Creuses</td>
<td>
<select name="extra3" id="extra0">
<option value="gekraakt">gekraakt</option>
<option value="niet-gekraakt">niet-gekraakt</option>
</select>
</td>
<td>€3/Stuk</td>
<td>
<input type="text" name="art3" id="art0" onkeypress="return numbersonly(this, event)" onkeyup="productprijs('3', this, 'subtotaal3')" style="width:50px">
</td>
<td id='subtotaal3'>0,00</td>
</tr>
<tr class="titel" id="seafood">
<td class="titelbeschrijving" width="30%">SEA FOOD</td>
<td width="15%">opties</td>
<td width="11%">prijs</td>
<td width="11%">aantal</td>
<td width="11%">bedrag</td>
</tr>
<tr class="prod4" id="rij1">
<td class="beschrijving">Wilde zalm gerookt met de hand gesneden</td>
<td>
</td>
<td>€10/100gram</td>
<td>
<input type="text" name="art4" id="art0" onkeypress="return numbersonly(this, event)" onkeyup="productprijs('10', this, 'subtotaal4')" style="width:50px">
</td>
<td id='subtotaal4'>0,00</td>
</tr>
<tr class="prod5" id="rij2">
<td class="beschrijving">Wulken</td>
<td>
</td>
<td>€3/100gram</td>
<td>
<input type="text" name="art5" id="art0" onkeypress="return numbersonly(this, event)" onkeyup="productprijs('3', this, 'subtotaal5')" style="width:50px">
</td>
<td id='subtotaal5'>0,00</td>
</tr>
<tr class="prod6" id="rij1">
<td class="beschrijving">Kreukels</td>
<td>
</td>
<td>€3/100gram</td>
<td>
<input type="text" name="art6" id="art0" onkeypress="return numbersonly(this, event)" onkeyup="productprijs('3', this, 'subtotaal6')" style="width:50px">
</td>
<td id='subtotaal6'>0,00</td>
</tr>
<tr class="prod7" id="rij2">
<td class="beschrijving">Ongepelde Zeebrugse garnalen</td>
<td>
</td>
<td>€2/100gram</td>
<td>
<input type="text" name="art7" id="art0" onkeypress="return numbersonly(this, event)" onkeyup="productprijs('2', this, 'subtotaal7')" style="width:50px">
</td>
<td id='subtotaal7'>0,00</td>
</tr>
<tr class="titel" id="Kreeft">
<td class="titelbeschrijving" width="30%">Kreeft & Langoustines</td>
<td width="15%">opties</td>
<td width="11%">prijs</td>
<td width="11%">aantal</td>
<td width="11%">bedrag</td>
</tr>
<tr class="prod9" id="rij1">
<td class="beschrijving">Kreeft in kruidenboter klaar voor de oven</td>
<td>
</td>
<td>600 gram €28</td>
<td>
<input type="text" name="art8" id="art0" onkeypress="return numbersonly(this, event)" onkeyup="productprijs('28', this, 'subtotaal9')" style="width:50px">
</td>
<td id='subtotaal9'>0,00</td>
</tr>
<tr class="prod10" id="rij2">
<td class="beschrijving">Kreeft in bouillon gekookt met garnituur</td>
<td>
</td>
<td>600 gram €28</td>
<td>
<input type="text" name="art9" id="art0" onkeypress="return numbersonly(this, event)" onkeyup="productprijs('28', this, 'subtotaal10')" style="width:50px">
</td>
<td id='subtotaal10'>0,00</td>
</tr>
<tr class="prod11" id="rij1">
<td class="beschrijving">Langoustines met kruiden boter klaar voor de oven</td>
<td>
</td>
<td>4 stuks €28</td>
<td>
<input type="text" name="art10" id="art0" onkeypress="return numbersonly(this, event)" onkeyup="productprijs('28', this, 'subtotaal11')" style="width:50px">
</td>
<td id='subtotaal11'>0,00</td>
</tr>
<tr class="titel" id="sugessties">
<td class="titelbeschrijving" width="30%">Suggestie</td>
<td width="15%">opties</td>
<td width="11%">prijs</td>
<td width="11%">aantal</td>
<td width="11%">bedrag</td>
</tr>
<tr class="prod112" id="rij1">
<td class="beschrijving">Plateau fruits de mer per twee personen: 3 maal 4 oesters, 2wulken, 2kreukels, 2ongepelde garnalen, 4 langoustines, 1 kreeft</td>
<td>
</td>
<td>per twee personen €84</td>
<td>
<input type="text" name="art11" id="art0" onkeypress="return numbersonly(this, event)" onkeyup="productprijs('84', this, 'subtotaal12')" style="width:50px">
</td>
<td id='subtotaal12'>0,00</td>
</tr>
<tr class="titel" id="champagne">
<td class="titelbeschrijving" width="30%">Chamapgne & Wijn</td>
<td width="15%">opties</td>
<td width="11%">prijs</td>
<td width="11%">aantal</td>
<td width="11%">bedrag</td>
</tr>
<tr class="prod13" id="rij1">
<td class="beschrijving">Champagne Ruinard</td>
<td>
</td>
<td>€38/fles</td>
<td>
<input type="text" name="art12" id="art0" onkeypress="return numbersonly(this, event)" onkeyup="productprijs('38', this, 'subtotaal13')" style="width:50px">
</td>
<td id='subtotaal13'>0,00</td>
</tr>
<tr class="prod14" id="rij2">
<td class="beschrijving">Champagne Laurenti</td>
<td>
</td>
<td>€21/fles</td>
<td>
<input type="text" name="art13" id="art0" onkeypress="return numbersonly(this, event)" onkeyup="productprijs('21', this, 'subtotaal14')" style="width:50px">
</td>
<td id='subtotaal14'>0,00</td>
</tr>
<tr class="prod15" id="rij1">
<td class="beschrijving">Blanquette de Limoux LeMoulin</td>
<td>
</td>
<td>€15/fles</td>
<td>
<input type="text" name="art14" id="art0" onkeypress="return numbersonly(this, event)" onkeyup="productprijs('15', this, 'subtotaal15')" style="width:50px">
</td>
<td id='subtotaal15'>0,00</td>
</tr>
<tr class="prod16" id="rij2">
<td class="beschrijving">Vedejo José Pariente</td>
<td>
</td>
<td>€15/fles</td>
<td>
<input type="text" name="art15" id="art0" onkeypress="return numbersonly(this, event)" onkeyup="productprijs('15', this, 'subtotaal16')" style="width:50px">
</td>
<td id='subtotaal16'>0,00</td>
</tr>
</tbody>
</table>
<br>
<br>
<table class="gegevens">
<tr>
<td>naam:</td>
<td>
<input type='text' name='naam'>
</td>
</tr>
<tr>
<td>telefoonnummer:</td>
<td>
<input type="tel" name="tel">
</td>
</tr>
<tr>
<td>email:</td>
<td>
<input type="email" name="email">
</td>
</tr>
<tr>
<td>datum:</td>
<td>
<input type="date" name="datum">
</td>
</tr>
<tr>
<td>tijdstip</td>
<td>
<input type="time" name="tijd">
</td>
</tr>
<tr>
</tr>
<tr>
<td>extra:</td>
<td>
<textarea name="textarea" style="width:250px;height:150px;"></textarea>
</td>
</tr>
</table>
<input type="submit" value="Ga verder">
<div id="resp" class="resp"></div>
</form>
<input type="hidden" name="aantalProducten" id="aantalProducten" value="16">
<p>click this for a total</p>
<button onclick="totaal()">Try</button>
<br>
<br>
<br>
</div>
</section>
So for now, the total price is displayed in a pop up (doesn't work), but then I was sure the button got its alert. Preferably it would be located in the table and updated on its own.
The button's on click event was calling a function totaal(). I could however find another function myFunction() doing some job of totalling the values. I think what you need is a function like this:
function totaal() {
totaalPrijs = 0;
aantalProd = parseInt(document.getElementById("aantalProducten").value);
for (var i = 0; i < aantalProd; i++) {
subPrijs = document.getElementById("subtotaal" + i).innerHTML;
if (subPrijs != "") {
totaalPrijs += parseFloat(subPrijs.replace(",", "."));
alert("€" + totaalPrijs);
}
}
}
Note that since you are trying to get the value from all the 16 text fields iteratively, the document.getElementById call needs to be passed a value like: subtotaal" + i.
Hope this works for you.

Categories

Resources