calculate grand total with javascript - javascript

I don't know how to get Grand total value
grand total is sum of all total
here is the code
<?php
$con = mysqli_connect('localhost', 'root', '', 'a.karat');
if(isset($_POST['product_id']))
{
$prno=$_POST['prno'];
$i=1;
$sql = mysqli_query($con,"select * from detail_pr where prNo='$prno'");
while ($r = mysqli_fetch_array($sql)) {
echo
'<tr>
<td><input type="checkbox" name="check[]" id="check'.$i.'" value="'.$i.'"></td>
<td><label for="productCode"></label>
<input type="text" name="productCode'.$i.'" id="productCode'.$i.'" readonly value="'.$r["productCode"].'" size="12" ></td>
<td><label for="productName"></label>
<input type="text" name="productName'.$i.'" id="productName'.$i.'" readonly value="'.$r["productName"].'"size="35" ></td>
<td><label for="qty"></label>
<input type="number" onkeyup="calc(this);" name="qty'.$i.'" id="qty'.$i.'" readonly value="'.$r["qty"].'" size="8" ></td>
<td><input type="number" onkeyup="calc(this);" name="price'.$i.'" id="price'.$i.'" size="10" min="1" max="99" onchange="calc(this);" ></td>
<td><input type="number" onkeyup="calc(this);" name="discount'.$i.'" id="discount'.$i.'" size="10" min="0" max="99" onchange="calc(this);"></td>
<td><input type="number" name="total'.$i.'" id="total'.$i.'" size="10" min="1" max="99" onchange="calc(this);" ></td>
</tr>';
$i++;
}
}
?>
<table width="400" border="0" align="right">
<tr>
<th scope="row">Grand Total</th>
<td>:</td>
<td><input name="grandtotal" id="grandtotal" type="text"></td>
</tr>
</table>
<script>
function calc(id) {
var row = id.parentNode.parentNode;
var quant = row.cells[3].getElementsByTagName('input')[0].value;
var price = row.cells[4].getElementsByTagName('input')[0].value;
var disc = row.cells[5].getElementsByTagName('input')[0].value;
if (disc == null || disc == '') {
res = parseFloat(quant) * parseFloat(price);
} else {
var res = (parseFloat(quant) * parseFloat(price)) - (parseFloat(quant) * parseFloat(price) * (parseFloat(disc) / 100));
}
row.cells[6].getElementsByTagName('input')[0].value = res;
}
</script>
I have manage to calculate total per row
now I need your help to sum all total and put the value in the grandtotal textbox

I guess on every change of a value of one of your input elements in your form the grand total should be updated, right? I 'd place an event listener on the form tag to keep it simple.
<form id="your-form" method="post" action="">
<!-- All your other inputs here -->
<input type="text" name="grandtotal" id="grandtotal">
</form>
<script>
document.querySelector('#your-form').addEventListener('change', function( event ) {
if (event.target.id && event.target.id !== 'grandtotal') {
var allTotals = document.querySelectorAll('input[name^="total"]'),
allTotalSum = 0;
Array.prototype.forEach.call(allTotals, function( element ) {
if (element.value) {
allTotalSum += parseFloat(element.value);
}
});
document.querySelector('#grandtotal').value = allTotalSum;
}
});
</script>
So on every change of one of your input fields the sum is updated. This code is untested.

Related

how to disable input text on condition

i would want to disable some input text when a certain condition is met. one input text value will be used as a key of the condition. imagine having 6 input and 2 getting data from table and these getting data from table 1 to store condition value. i want a scenario like, if text2.value is 'test' then text3 and text 4 should be disable.
this is what i have done
am tagging js,jq and hmtl maybe one could provide an assistance
html
<input type="hidden" name="ttype[<?php echo $ix ?>]" value="<?php echo
$rowx['testtype']; ?>"/>
<td colspan="0"> Result <br>
<div>
<select name="negpos[<?php echo $ix ?>]" style='width:50px'>
<option selected value=''> Select One </option>
<option value='Pos'> Positive</option>
<option value='Neg'> Negative</option>
<option value='N/P'> Not Provided</option>
</select>
<span id="sresultInfo">
</span>
</div>
</td>
<td><input type="text" name="WBC[<?php echo $ix ?>]"size ="3" /></td>
<td><input type="text" name="HGB[<?php echo $ix ?>]"size ="3" /></td>
<td> <input type="text" name="RBC[<?php echo $ix ?>]" size ="3" value=""/></td>
<td><input type="text" name="Lymph[<?php echo $ix ?>]"size ="3"/></td>
<td><input type="text" name="MCV[<?php echo $ix ?>]" size ="3"/></td>
<td><input type="text" name="Gran[<?php echo $ix ?>]" size ="3"/></td>
<td> <input type="text" name="MCH[<?php echo $ix ?>]" size ="3"/> </td>
js
$(document).ready(function(){
var ttyp = document.getElementById("ttype").value ;
if (ttyp = "MPP" ){
document.getElementById('WBC').disabled = true;
document.getElementById('HBG').disabled = true;
document.getElementById('RBC').disabled = true;
} else {
document.getElementById('WBC').disabled = false;
document.getElementById('HGB').disabled = false;
document.getElementById('RBC').disabled = false;
}
});
You can do something similar to this. The disabletext represents the text to match to disable and disablefieldids is the list of comma seperated value which contain id of the field to disable.
$('input').on('change', function() {
var conditions = $(this).data();
var inputValue = $(this).val();
if(inputValue == conditions.disabletext) {
conditions.disablefieldids.split(",").map(function(id) {
$('#'+id).attr('disabled', 'disabled');
})
}else {
conditions.disablefieldids.split(",").map(function(id) {
$('#'+id).removeAttr('disabled');
})
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>
<input type="text" data-disabletext="test" data-disablefieldids="HGB,RBC" name="WBC"size ="3" />
</td>
<td><input type="text" id="HGB" name="HGB"size ="3" /></td>
<td> <input type="text" id="RBC" name="RBC" size ="3" value=""/></td>
<td><input type="text" id="Lymph" name="Lymph"size ="3"/></td>
<td><input type="text" id="MCV" name="MCV" size ="3"/></td>
<td><input type="text" id="Gran" name="Gran" size ="3"/></td>
<td> <input type="text" id="MCH" name="MCH" size ="3"/> </td>
</tr>
</table>
Instead of storing disable text and fields to input attributes I would like create one general object so it will give us more usability,
const InputCondition = [
{"disabletext":"Test","disablefieldids":["HGB","RBC"]},
{"disabletext":"ABC","disablefieldids":["MCV","MCV"]}
];
here is the on keyup initialization (change as per your need)
$('#ttype').keyup(function () {
func_makeInputdisable($(this).val());
});
// you can call this onload // pass the text value in param.
function func_makeInputdisable(lookingForText) {
let matches = InputCondition.find(x =>
x.disabletext.toLowerCase() == lookingForText.trim().toLowerCase());
if (typeof (matches) != 'undefined') {
matches = matches.disablefieldids;
//Remove all the disable inputs if in need
$('.AllInputClass').removeAttr('disabled');
if (matches.length > 0) {
$.each(matches, (index, inputID) => {
let $ele = $(`#${inputID}`);
if (typeof ($ele) != 'undefined')
$ele.attr('disabled', 'disabled');
});
}
}
else {
$('.AllInputClass').removeAttr('disabled');
}
}
// To enable textbox just add the same class on each input and use like,
$('.AllInputClass').removeAttr('disabled'); placed in comment above function with class name "AllInputClass"

How to calculate my inputs to the total id in realtime with pure javascript only?

My problem with this is it doesnt respond, i made sure to load with a document.addEventListener('DOMContentLoaded', function(event) {
which helped me reset my inputs with that however, when getting the actual calculation there seems to be no updating, what approach should i look into,
Heres my code,
document.addEventListener('DOMContentLoaded', function(event) {
document.getElementById("input").onkeyup = function() {calc()};
function calc(){
var in_bottles = parseInt(document.getElementById('in_bottles').value,);
var in_bags = parseInt(document.getElementById('in_bags').value, "");
var in_wrapping = parseInt(document.getElementById('in_wrapping').value, "");
var in_yogurt = parseInt(document.getElementById('in_yogurt').value, "");
var in_takeout = parseInt(document.getElementById('in_takeout').value, "");
var in_cups = parseInt(document.getElementById('in_cups').value, "");
var in_packaging = parseInt(document.getElementById('in_packaging').value, "");
var in_detergent = parseInt(document.getElementById('in_detergent').value, "");
var in_shampoo = parseInt(document.getElementById('in_shampoo').value, "");
var in_toothbrushes = parseInt(document.getElementById('in_toothbrushes').value, "");
var in_toothpaste = parseInt(document.getElementById('in_toothpaste').value, "");
document.getElementById('total_per_year').innerHTML = in_bottles + in_bags + in_wrapping + in_yogurt + in_yogurt + in_takeout + in_cups + in_packaging + in_detergent + in_shampoo + in_toothbrushes + in_toothpaste;
From html it looks like this, its apart of a coursework, so the restrictions are i cant edit html, so i think i may need to approach it like this? heres my attempt anyway
Food & Kitchen
<table>
<tr>
<td><label for="in_bottles">Plastic bottles</label></td>
<td><input id="in_bottles" name="bottles" type="number" value="0" min="0" data-weight="0.730"> / week</td>
</tr><tr>
<td><label for="in_bags">Plastic bags</label></td>
<td><input id="in_bags" name="bags" type="number" value="0" min="0" data-weight="0.417"> / week</td>
</tr><tr>
<td><label for="in_wrapping">Food wrapping</label></td>
<td><input id="in_wrapping" name="wrapping" type="number" value="0" min="0" data-weight="0.583"> / week</td>
</tr><tr>
<td><label for="in_yogurt">Yogurt, cream, etc. containers</label></td>
<td><input id="in_yogurt" name="yogurt" type="number" value="0" min="0" data-weight="0.383"> / week</td>
</tr>
</table>
</section>
<section id="sec_packaging">
<h2>Disposable Containers & Packaging</h2>
<table>
<tr>
<td><label for="in_takeout">Take-away plastic boxes</label></td>
<td><input id="in_takeout" name="takeout" type="number" value="0" min="0" data-weight="0.383"> / month</td>
</tr><tr>
<td><label for="in_cups">Take-away cups</label></td>
<td><input id="in_cups" name="cups" type="number" value="0" min="0" data-weight="0.240"> / month</td>
</tr><tr>
<td><label for="in_packaging">Plastic-wrapped packages</label></td>
<td><input id="in_packaging" name="packaging" type="number" value="0" min="0" data-weight="0.834"> / month</td>
</tr>
</table>
</section>
<section id="sec_washing">
<h2>Bathroom & Laundry</h2>
<table>
<tr>
<td><label for="in_detergent">Detergent & cleaning product bottles</label></td>
<td><input id="in_detergent" name="detergent" type="number" value="0" min="0" data-weight="0.120"> / year</td>
</tr><tr>
<td><label for="in_shampoo">Shampoo, conditioner & toiletries</label></td>
<td><input id="in_shampoo" name="shampoo" type="number" value="0" min="0" data-weight="0.080"> / year</td>
</tr><tr>
<td><label for="in_toothbrushes">Plastic toothbrushes</label></td>
<td><input id="in_toothbrushes" name="toothbrushes" type="number" value="0" min="0" data-weight="0.020"> / year</td>
</tr><tr>
<td><label for="in_toothpaste">Toothpaste</label></td>
<td><input id="in_toothpaste" name="toothpaste" type="number" value="0" min="0" data-weight="0.015"> / year</td>
</tr>
</table>
</section>
Your Plastic Footprint
<p>Your estimated plastic footprint is <span id="total_per_year">0</span> kg / year.</p>
<p>The gobal average is ~50 kg / year.</p>
<p>The USA average is ~84 kg / year.</p>
<p>The Eurpean average is ~30 kg / year.</p>
<p><button id="reset">Reset calculator</button></p>
</section>
EDIT: im back at my computer, here is a whole new answer that cover the old one aswell:
EDIT 2: i added the use of dataset to get the data-weight attribute you use in your example
const btn = document.getElementById('reset');
const total = document.getElementById('total_per_year');
const htmlCollection = document.getElementsByTagName("input");
let inputs = [...htmlCollection];
let totalValue = 0;
function reset() {
inputs.forEach(input => {
input.value = 0
})
total.innerText = 0;
}
//Add eventlistneres for "change" and "keyup" to all inputs and execute sumTotal when event is triggered
//Note that change is triggered when the user "leaves" the input box or clicks the increment arrows so keyup is added to register direct inputs and update before the user leaves the box
function addEventListeners() {
inputs.forEach(input => {
input.addEventListener('change', () => {
totalValue = 0;
sumTotal();
});
input.addEventListener('keyup', () => {
totalValue = 0;
sumTotal();
});
})
}
//Summerize the value of each imput and set the totalValue and eliminate crazy decimals then display it
function sumTotal(value) {
inputs.forEach(input => {
totalValue += Number(input.value) * Number(input.dataset.weight);
})
total.innerText = totalValue.toFixed(2);
}
//When the DOM content is loaded we run the function that adds the eventListeners
document.addEventListener('DOMContentLoaded', () => {
addEventListeners();
})
btn.addEventListener("click", () => {
reset()
})
<input type="number" value="0" data-weight="0.43" />
<input type="number" value="0" data-weight="0.71" />
<input type="number" value="0" data-weight="1.65" />
<input type="number" value="0" data-weight="1.19" />
<input type="number" value="0" data-weight="2.44" />
<p>Your estimated plastic footprint is <span id="total_per_year">0</span> kg / year.</p>
<button id="reset">Reset</button>

calculate salesperson's sales + commission from an html form user fills out/text input

The user fills out the form below based upon how many of the items they sold.
The calculator then calculates how much the salesperson sold into the blanks below + how much they earned + 200 dollars additional + 9% commission on total sales... and then the form outputs the results.
round the outputted results to 2 decimal places.
check for valid numeric input
make sure the number of items sold is < 0, as nobody sells negative number of items.
right-justify all amounts.
I have written out what I think the functions should be about, without proper syntax. I am super green with javascript and pretty much am only good at HTML sadly. I need help making what I have correspond to the form fields properly... this is all very overwhelming. Any Explanation is helpful.
<h1>Sales Commission Calculator</h1>
<hr>
<section>
<form name="salesperson_total">
Salesperson: <input type="text" title="Please make sure that the salesperson's name is spelled correctly" name="sp" size="20">
<br>
<br>
<h3>Input the number of items sold for each item number:</h3>
Item 1: <input class="t" type="text" name="num_item1" size="8" value="num_item1"><br>
Item 2: <input class="t" type="text" name="num_item2" size="8" value="num_item2"><br>
Item 3: <input class="t" type="text" name="num_item3" size="8" value="num_item3"><br>
Item 4: <input class="t" type="text" name="num_item4" size="8" value="num_item4"><br><br>
<input type="button" value="Submit">
<input type="reset" value="Reset"><br><br>
<table>
<tr>
<th>Item #</th>
<th>Price</th>
<th>Number Sold</th>
<th>Total</th>
</tr>
<tr>
<td>1</td>
<td>$239.99</td>
<td><input type="text" class="t" name="int_item1"></td>
<td><input type="text" class="t" name="total_item1"></td>
</tr>
<tr>
<td>2</td>
<td>$129.75</td>
<td><input type="text" class="t" name="int_item2"></td>
<td><input type="text" class="t" name="total_item2"></td>
</tr>
<tr>
<td>3</td>
<td>$99.95</td>
<td><input type="text" class="t" name="int_item3"></td>
<td><input type="text" class="t" name="total_item3"></td>
</tr>
<tr>
<td>4</td>
<td>$350.89</td>
<td><input type="text" class="t" name="int_item4"></td>
<td><input type="text" class="t" name="total_item4"></td>
</tr>
<tr>
<td colspan="3">Total Amount Sold:</td>
<td><input type="text" class="t" name="final_total"></td>
</tr>
<tr>
<td colspan="3">Total Weekly Earnings:</td>
<td><input type="text" class="t" name="salary"></td>
</tr>
</table>
</form>
</section>
<br>
<script>
var num_item1 = "";
var num_item2 = "";
var num_item3 = "";
var num_item4 = "";
var price1 = 239.99;
var price2 = 129.75;
var price3 = 99.95;
var price4 = 350.89;
var int_item1 = "";
var int_item2 = "";
var int_item3 = "";
var int_item4 = "";
var total_item1;
var total_item2;
var total_item3;
var total_item4;
var comm;
function numberSold() {
num_item1
num_item2
num_item3
num_item4
}
function totalSold() {
total_item1 = num_item1 * price1;
total_item2 = num_item2 * price2;
total_item3 = num_item3 * price3;
total_item4 = num_item4 * price4;
}
function amountSold() {
total_item1 + total_item2 + total_item3 + total_item4;
}
function getComm() {
comm = Math.floor(9/amountSold*100);
}
function weeklyEarned() {
amountSold + comm + 200
document.write();
}
</script>
</section>
</body>
</html>
//see above for expected results in description.
I did this quickly and this should suffice to act as a guide:
<h1>Sales Commission Calculator</h1>
<hr>
<section>
<form name="salesperson_total">
Salesperson: <input type="text" title="Please make sure that the salesperson's name is spelled correctly" name="sp" size="20">
<br>
<br>
<h3>Input the number of items sold for each item number:</h3>
Item 1: <input class="t" type="text" name="num_item1" id="item1" size="8" value="0" style="text-align:right;" onkeyup="checkNumItems();"><br>
Item 2: <input class="t" type="text" name="num_item2" id="item2" size="8" value="0" style="text-align:right;" onkeyup="checkNumItems();"><br>
Item 3: <input class="t" type="text" name="num_item3" id="item3" size="8" value="0" style="text-align:right;" onkeyup="checkNumItems();"><br>
Item 4: <input class="t" type="text" name="num_item4" id="item4" size="8" value="0" style="text-align:right;" onkeyup="checkNumItems();"><br>
<span id="msg" style="color:red;"></span><br><br> <!--This element is used to display an error message if any item entered is less than zero-->
<input type="button" value="Submit" id="submitBtn" onclick="calculate()">
<input type="reset" value="Reset" onclick="reset()"><br><br>
<table>
<tr>
<th>Item #</th>
<th>Price</th>
<th>Number Sold</th>
<th>Total</th>
</tr>
<tr>
<td>1</td>
<td>$239.99</td>
<td><input type="text" class="t" name="int_item1" id="int_item1" style="text-align:right;"></td>
<td><input type="text" class="t" name="total_item1" id="total_item1" style="text-align:right;"></td>
</tr>
<tr>
<td>2</td>
<td>$129.75</td>
<td><input type="text" class="t" name="int_item2" id="int_item2" style="text-align:right;"></td>
<td><input type="text" class="t" name="total_item2" id="total_item2" style="text-align:right;"></td>
</tr>
<tr>
<td>3</td>
<td>$99.95</td>
<td><input type="text" class="t" name="int_item3" id="int_item3" style="text-align:right;"></td>
<td><input type="text" class="t" name="total_item3" id="total_item3" style="text-align:right;"></td>
</tr>
<tr>
<td>4</td>
<td>$350.89</td>
<td><input type="text" class="t" name="int_item4" id="int_item4" style="text-align:right;"></td>
<td><input type="text" class="t" name="total_item4" id="total_item4" style="text-align:right;"></td>
</tr>
<tr>
<td colspan="3">Total Amount Sold:</td>
<td><input type="text" class="t" name="final_total" id="final_total" style="text-align:right;"></td>
</tr>
<tr>
<td colspan="3">Total Weekly Earnings:</td>
<td><input type="text" class="t" name="salary" id="salary" style="text-align:right;"></td>
</tr>
</table>
</form>
</section>
<br>
<!--Javascript-->
<script>
//Declare and initialize all variables
var num_item1 = "";
var num_item2 = "";
var num_item3 = "";
var num_item4 = "";
var price1 = 239.99;
var price2 = 129.75;
var price3 = 99.95;
var price4 = 350.89;
var int_item1 = "";
var int_item2 = "";
var int_item3 = "";
var int_item4 = "";
var total_item1 = 0;
var total_item2 = 0;
var total_item3 = 0;
var total_item4 = 0;
var comm = 0;
var earnings = 0;
//As the user enters a value in the item fields check if the number of items entered by the user is less than zero
function checkNumItems(){
if(document.getElementById('item1').value < 0 || document.getElementById('item2').value < 0 || document.getElementById('item3').value < 0 || document.getElementById('item4').value < 0){
//Display an error message if either one of the items is less than zero
document.getElementById('msg').innerHTML = "Error: Values cannot be less than 0";
//Disable the submit button if either one of the items is less than zero
document.getElementById("submitBtn").disabled = true;
}else{
//Remove (or do not display) an error message if all items are more than 0
document.getElementById('msg').innerHTML = "";
//Enable submit button if all items are greater than zero
document.getElementById("submitBtn").disabled = false;
} }
//Function used to calculate and fill in all fields when the user press Submit
function calculate(){
//Get the values the user entered
num_item1 = document.getElementById('item1').value;
num_item2 = document.getElementById('item2').value;
num_item3 = document.getElementById('item3').value;
num_item4 = document.getElementById('item4').value;
//Set the values into the fields of the column 'Number Sold'
document.getElementById('int_item1').value = num_item1;
document.getElementById('int_item2').value = num_item2;
document.getElementById('int_item3').value = num_item3;
document.getElementById('int_item4').value = num_item4;
//Calculate the total for each item
total_item1 = num_item1 * price1;
total_item2 = num_item2 * price2;
total_item3 = num_item3 * price3;
total_item4 = num_item4 * price4;
//Set the total for each fields of the 'Total' column
document.getElementById('total_item1').value = total_item1;
document.getElementById('total_item2').value = total_item2;
document.getElementById('total_item3').value = total_item3;
document.getElementById('total_item4').value = total_item4;
//Calculate the 'Total Amount Sold' field
amountSold = total_item1 + total_item2 + total_item3 + total_item4;
//Set (fill in) the 'Total Amount Sold' field
document.getElementById('final_total').value = amountSold;
//Calculate the commission
comm = Math.floor(9/amountSold*100);
//Caclulate the earnings
earnings = amountSold + comm + 200;
//Set the 'Total Weekly Earnings' field
document.getElementById('salary').value = earnings;
}
//Function used to Reset the fields the salesperson enters when they press Reset
function reset(){
document.getElementById('item1').value = 0;
document.getElementById('item2').value = 0;
document.getElementById('item3').value = 0;
document.getElementById('item4').value = 0;
}
</script>

How to access HTML array object in javascript?

sorry for asking simple question. I am really a beginner in Javascript. I need to access my HTML array form object in my javascript, but I don't know how to do it.
The goal is to trigger the alert in javascript so the browser will display message according to the condition in javascript. Here is my code :
checkScore = function()
{
//I don't know how to access array in HTML Form, so I just pretend it like this :
var student = document.getElementByName('row[i][student]').value;
var math = document.getElementByName('row[i][math]').value;
var physics = document.getElementByName('row[i][physics]').value;
if (parseInt(math) >= 80 ) {
alert(student + " ,You are good at mathematic");
}
if (parseInt(physics) >= 80 ){
alert(student + " ,You are good at physics");
}
student_score.row[i][otherinfo].focus();
student_score.row[i][otherinfo].select();
}
<h2>HTML Forms</h2>
<form name="student_score" action="/action_page.php">
<table border=1>
<thead>
<td>Student</td>
<td>Math Score</td>
<td>Physics Score</td>
<td>Other info</td>
</thead>
<tbody>
<tr>
<td><input type="text" name="row[1][student]"></td>
<td><input type="number" name="row[1][math]" onblur="checkScore()" min="0" max="100"></td>
<td><input type="number" name="row[1][physics]" onblur="checkScore()" min="0" max="100"></td>
<td><input type="text" name="row[1][otherinfo]"></td>
</tr>
<tr>
<td><input type="text" name="row[2][student]"></td>
<td><input type="number" name="row[2][math]" onblur="checkScore()" min="0" max="100"></td>
<td><input type="number" name="row[2][physics]" onblur="checkScore()" min="0" max="100"></td>
<td><input type="text" name="row[2][otherinfo]"></td>
</tr>
<tr>
<td>
<input type="submit" value="Submit">
</td>
</tr>
</tbody>
</table>
</form>
<p>If you click the "Submit" button, it will save the data.</p>
We are going to leverage few things here to streamline this.
The first is Event Listeners, this removes all javascript from your HTML. It also keeps it more dynamic and easier to refactor if the table ends up having rows added to it via javascript.
Next is parentNode, which we use to find the tr that enclosed the element that was clicked;
Then we use querySelectorAll with an attribute selector to get our target fields from the tr above.
/*This does the work*/
function checkScore(event) {
//Get the element that triggered the blur
var element = event.target;
//Get our ancestor row (the parent of the parent);
var row = element.parentNode.parentNode;
//Use an attribute selector to get our infor from the row
var student = row.querySelector("[name*='[student]']").value;
var math = row.querySelector("[name*='[math]']").value;
var physics = row.querySelector("[name*='[physics]']").value;
var otherField = row.querySelector("[name*='[otherinfo]']");
if (parseInt(math, 10) >= 80) {
alert(student + " ,You are good at mathematic");
}
if (parseInt(physics, 10) >= 80) {
alert(student + " ,You are good at physics");
}
otherField.focus();
otherField.select();
}
/*Wire Up the event listener*/
var targetElements = document.querySelectorAll("input[name*='math'], input[name*='physics']");
for (var i = 0; i < targetElements.length; i++) {
targetElements[i].addEventListener("blur", checkScore);
}
<h2>HTML Forms</h2>
<form name="student_score" action="/action_page.php">
<table border=1>
<thead>
<tr>
<td>Student</td>
<td>Math Score</td>
<td>Physics Score</td>
<td>Other info</td>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="row[1][student]" class='student'></td>
<td><input type="number" name="row[1][math]" min="0" max="100"></td>
<td><input type="number" name="row[1][physics]" min="0" max="100"></td>
<td><input type="text" name="row[1][otherinfo]"></td>
</tr>
<tr>
<td><input type="text" name="row1[2][student]"></td>
<td><input type="number" name="row[2][math]" min="0" max="100"></td>
<td><input type="number" name="row[2][physics]" min="0" max="100"></td>
<td><input type="text" name="row[2][otherinfo]"></td>
</tr>
<tr>
<td>
<input type="submit" value="Submit">
</td>
</tr>
</tbody>
</table>
</form>
Well, it follows your line of code exactly as it is (because you said you do not want to change the code too much).
<h2>HTML Forms</h2>
<form name="student_score" action="/action_page.php">
<table border=1>
<thead>
<td>Student</td>
<td>Math Score</td>
<td>Physics Score</td>
<td>Other info</td>
</thead>
<tbody>
<tr>
<td><input type="text" name="row[1][student]"></td>
<td><input type="number" name="row[1][math]" onblur="checkScore(this)" min="0" max="100"></td>
<td><input type="number" name="row[1][physics]" onblur="checkScore(this)" min="0" max="100"></td>
<td><input type="text" name="row[1][otherinfo]"></td>
</tr>
<tr>
<td><input type="text" name="row1[2][student]"></td>
<td><input type="number" name="row[2][math]" onblur="checkScore(this)" min="0" max="100"></td>
<td><input type="number" name="row[2][physics]" onblur="checkScore(this)" min="0" max="100"></td>
<td><input type="text" name="row[2][otherinfo]"></td>
</tr>
<tr>
<td>
<input type="submit" value="Submit">
</td>
</tr>
</tbody>
</table>
</form>
JavaScript [Edited again using part of the #Jon P code, the query selector is realy more dynamic, and the value of the "other" field you requested is commented out]
//pass element to function, in html, only add [this] in parenteses
checkScore = function (element) {
//Get our ancestor row (the parent of the parent);
var row = element.parentNode.parentNode;
//Use an attribute selector to get our infor from the row
var student = row.querySelector("[name*='[student]']").value;
var math = row.querySelector("[name*='[math]']").value;
var physics = row.querySelector("[name*='[physics]']").value;
var other = row.querySelector("[name*='[otherinfo]']");
if (parseInt(math) >= 80) {
//other.value = student + " ,You are good at mathematic";
alert(student + " ,You are good at mathematic");
}
if (parseInt(physics) >= 80) {
//other.value = student + " ,You are good at physics";
alert(student + " ,You are good at physics");
}
otherField.focus();
otherField.select();
}
Tested :), and sorry about my english!
Try that, haven't tested it
var form = document.getElementsByName("student_score")[0];
var students = form.getElementsByTagName("tr");
for(var i = 0; i < students.length; i++){
var student = students[i].childnodes[0].value;
var math = students[i].childnodes[1].value;
var physics = students[i].childnodes[2].value;
if (parseInt(math) >= 80 ) {
alert(student + " ,You are good at mathematic");
}
if (parseInt(physics) >= 80 ){
alert(student + " ,You are good at physics");
}
}

Why does the total from last row is not calculating the sum?

I am doing a project that involves making an estimate and adding up does results. I am using the method GET and using some of the the info from the url. Also i am using WordPress to build the Web Page. Problem is that sum of the TOTAL column is not working and showing in the TOTAL row that i made. Is not an error but i think I need to add one more piece of code or change something in the javascript. So why does the id:"total" not showing the sum of the whole column? is the total.value wrong? does the id:"system_total" have a problem?
Here is how the HTML looks like:
<form >
<h2>Cotizacion</h2>
<table class="Cotization">
<tbody>
<tr>
<th style="width:25%;font-size:16px;text-align:center;">Description</th>
<th style="width:15%;" class="qtyhd" title="qtytt">Qty</th>
<th style="width:15%;" class="ratehd" title="ratett">Rate</th>
<th style="width:15%;" class="tlhd" title="totaltt">Total</th>
</tr>
<tr>
<td>PV Grid Tied System</td>
<td> <input id="system_qty" name="system_qty" value="1" type="number" /></td>
<td> <input id="system_rate" name="system_rate" value="0" type="number" /></td>
<td> <output id="system_total"> </output></td>
</tr>
<tr>
<td>Solar Modules 250w</td>
<td> <input id="modules_qty" name="modules_qty" value="0" type="number" /></td>
<td> <input id="modules_rate" name="modules_rate" value="0" type="number" /></td>
<td> <output id="modules_total"> </output></td>
</tr>
<tr>
<td>Inverter</td>
<td> <input id="inverter_qty" name="inverter_qty" value="1" type="number" /></td>
<td> <input id="inverter_rate" name="inverter_rate" value="0" type="number" /></td>
<td> <output id="inverter_total"> </output></td>
</tr>
<tr>
<td>Aluminum Fames</td>
<td> <input id="aluminum_qty" name="aluminum_qty" value="0" type="number" /></td>
<td> <input id="aluminum_rate" name="aluminum_rate" value="0" type="number" /></td>
<td> <output id="aluminum_total"> </output></td>
</tr>
<tr>
<td>Service Disconnect</td>
<td> <input id="servicedt_qty" name="servicedt_qty" value="1" type="number" /></td>
<td> <input id="servicedt_rate" name="servicedt_rate" value="0" type="number" /></td>
<td> <output id="servicedt_total"> </output></td>
</tr>
<tr>
<td>Installation</td>
<td> <input id="installation_qty" name="installation_qty" value="1" type="number" /></td>
<td> <input id="installation_rate" name="installation_rate" value="0" type="number" /></td>
<td> <output id="installation_total"> </output></td>
</tr>
<tr>
<td>Down Payment</td>
<td> <input id="dnpayment_qty" name="dnpayment_qty" value="-1" type="number" /></td>
<td> <input id="dnpayment_rate" name="dnpayment_rate" value="0" type="number" /></td>
<td> <output id="dnpayment_total"> </output></td>
</tr>
<tr>
<td>Total </td>
<td> </td>
<td> </td>
<td> <input id="total" name="total"/></td>
</tr>
</tbody>
</table>
</form>
And here is the javascript that might have the problem:
<script>
document.addEventListener('DOMContentLoaded', function () {
var system_size = Number(getParameterByName('system_size'));
var system_rate_input = document.getElementById('system_rate');
var modules_qty = document.getElementById('modules_qty');
var aluminum_qty = document.getElementById('aluminum_qty');
var systemTotal = Number(document.getElementById('system_total').innerText);
var moduleTotal = Number(document.getElementById('modules_total').innerText);
var inverterTotal = Number(document.getElementById('inverter_total').innerText);
var aluminumTotal = Number(document.getElementById('aluminum_total').innerText);
var servicedtTotal = Number(document.getElementById('servicedt_total').innerText);
var installationTotal = Number(document.getElementById('installation_total').innerText);
var dnpaymentTotal = Number(document.getElementById('dnpayment_total').innerText);
var total = document.getElementById('total');
modules_qty.value = Number(system_size) * 4;
aluminum_qty.value = Number(modules_qty.value);
system_rate_input.value = 2.9 * 1000 * 1.2 * system_size;
updateSystemTotal()
updateModulesTotal()
updateInverterTotal()
updateAluminumTotal()
updateServiceTotal()
updateInstallationTotal()
updateDownPaymentTotal()
total.value = Number(systemTotal) + Number(moduleTotal) + Number(inverterTotal) + Number(aluminumTotal) + Number(servicedtTotal) + Number(installationTotal) + Number(dnpaymentTotal);
})
// FIRST ROW
function updateSystemTotal() {
var output = document.getElementById('system_total');
var quantity = Number(document.getElementById('system_qty').value);
var system_rate = Number(document.getElementById('system_rate').value);
output.innerText = quantity * system_rate;
}
document.getElementById('system_rate').addEventListener('change', updateSystemTotal)
document.getElementById('system_qty').addEventListener('change', updateSystemTotal)
// Second ROW
function updateModulesTotal() {
var output = document.getElementById('modules_total');
var quantity = Number(document.getElementById('modules_qty').value);
var modules_rate = Number(document.getElementById('modules_rate').value);
output.innerText = quantity * modules_rate;
}
document.getElementById('modules_rate').addEventListener('change', updateModulesTotal)
document.getElementById('modules_qty').addEventListener('change', updateModulesTotal)
// Third ROW
function updateInverterTotal() {
var output = document.getElementById('inverter_total');
var quantity = Number(document.getElementById('inverter_qty').value);
var inverter_rate = Number(document.getElementById('inverter_rate').value);
output.innerText = quantity * inverter_rate;
}
document.getElementById('inverter_rate').addEventListener('change', updateInverterTotal)
document.getElementById('inverter_qty').addEventListener('change', updateInverterTotal)
// Fourth ROW
function updateAluminumTotal() {
var output = document.getElementById('aluminum_total');
var quantity = Number(document.getElementById('aluminum_qty').value);
var aluminum_rate = Number(document.getElementById('aluminum_rate').value);
output.innerText = quantity * aluminum_rate;
}
document.getElementById('aluminum_rate').addEventListener('change', updateAluminumTotal)
document.getElementById('aluminum_qty').addEventListener('change', updateAluminumTotal)
// Fith ROW
function updateServiceTotal() {
var output = document.getElementById('servicedt_total');
var quantity = Number(document.getElementById('servicedt_qty').value);
var servicedt_rate = Number(document.getElementById('servicedt_rate').value);
output.innerText = quantity * servicedt_rate;
}
document.getElementById('servicedt_rate').addEventListener('change', updateServiceTotal)
document.getElementById('servicedt_qty').addEventListener('change', updateServiceTotal)
// Six ROW
function updateInstallationTotal() {
var output = document.getElementById('installation_total');
var quantity = Number(document.getElementById('installation_qty').value);
var installation_rate = Number(document.getElementById('installation_rate').value);
output.innerText = quantity * installation_rate;
}
document.getElementById('installation_rate').addEventListener('change', updateInstallationTotal)
document.getElementById('installation_qty').addEventListener('change', updateInstallationTotal)
//Seventh ROW
function updateDownPaymentTotal() {
var output = document.getElementById('dnpayment_total');
var quantity = Number(document.getElementById('dnpayment_qty').value);
var dnpayment_rate = Number(document.getElementById('dnpayment_rate').value);
output.innerText = quantity * dtpayment_rate;
}
document.getElementById('dnpayment_rate').addEventListener('change', updateDownPaymentTotal)
document.getElementById('dnpayment_qty').addEventListener('change', updateDownPaymentTotal)
// DON't TOUCH ANYTHING BELOW THIS POINT!!!
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
</script>
var systemTotal = Number(document.getElementById('system').innerText);
There is no element called "system" in the snippets you provided. Are you sure you don't need to get the value from "system_total"?
Edit:
Total is showing 0 at the beginning, because the subtotals aren't initialized. To fix this, you can use your update functions before calculating the total.
document.addEventListener('DOMContentLoaded', function () {
var system_size = Number(getParameterByName('system_size'));
var system_rate_input = document.getElementById('system_rate');
var modules_qty = document.getElementById('modules_qty');
var aluminum_qty = document.getElementById('aluminum_qty');
var total = document.getElementById('total');
modules_qty.value = Number(system_size) * 4;
aluminum_qty.value = Number(modules_qty.value);
system_rate_input.value = 2.9 * 1000 * 1.2 * system_size;
updateSystemTotal();
updateModulesTotal();
updateInverterTotal();
updateAluminumTotal();
updateServiceTotal();
updateInstallationTotal();
updateDownPaymentTotal();
updateTotal();
})
function updateTotal() {
var total = document.getElementById('total');
var systemTotal = Number(document.getElementById('system_total').innerText);
var moduleTotal = Number(document.getElementById('modules_total').innerText);
var inverterTotal = Number(document.getElementById('inverter_total').innerText);
var aluminumTotal = Number(document.getElementById('aluminum_total').innerText);
var servicedtTotal = Number(document.getElementById('servicedt_total').innerText);
var installationTotal = Number(document.getElementById('installation_total').innerText);
var dnpaymentTotal = Number(document.getElementById('dnpayment_total').innerText);
total.value = Number(systemTotal) + Number(moduleTotal) + Number(inverterTotal) + Number(aluminumTotal) + Number(servicedtTotal) + Number(installationTotal) + Number(dnpaymentTotal);
}
Further, you are updating the subtotals as soon as the user edits Quantities or Rates, but you are not updating the "Total" value.
You could call updateTotal() in your own update functions to solve this issue:
function updateSystemTotal() {
var output = document.getElementById('system_total');
var quantity = Number(document.getElementById('system_qty').value);
var system_rate = Number(document.getElementById('system_rate').value);
output.innerText = quantity * system_rate;
updateTotal();
}
Copy my code and Run it :
javascript(1.js) :
function rr() {
var system_size = document.getElementById('system_qty').value;
var system_rate_input = document.getElementById('system_rate').value;
var modules_qty = document.getElementById('modules_qty').value;
var modules_rate = document.getElementById('modules_rate').value;
var inverter_qty = document.getElementById('inverter_qty').value;
var inverter_rate = document.getElementById('inverter_rate').value;
var aluminum_qty = document.getElementById('aluminum_qty').value;
var aluminum_rate = document.getElementById('aluminum_rate').value;
var servicedt_qty = document.getElementById('servicedt_qty').value;
var servicedt_rate = document.getElementById('servicedt_rate').value;
var installation_qty = document.getElementById('installation_qty').value;
var installation_rate = document.getElementById('installation_rate').value;
var dnpayment_qty = document.getElementById('dnpayment_qty').value;
var dnpayment_rate = document.getElementById('dnpayment_rate').value;
var systemTotal = system_size * system_rate_input;
document.getElementById('system_total').innerHTML = systemTotal;
var moduleTotal = modules_rate * modules_qty;
document.getElementById('modules_total').innerHTML = moduleTotal;
var inverterTotal = inverter_qty * inverter_rate;
document.getElementById('inverter_total').innerHTML = inverterTotal;
var aluminumTotal =aluminum_qty * aluminum_rate;
document.getElementById('aluminum_total').innerHTML = aluminumTotal;
var servicedtTotal = servicedt_qty * servicedt_rate;
document.getElementById('servicedt_total').innerHTML = servicedtTotal;
var installationTotal = installation_qty * installation_rate;
document.getElementById('installation_total').innerHTML = installationTotal;
var dnpaymentTotal = dnpayment_qty * dnpayment_rate;
document.getElementById('dnpayment_total').innerHTML = dnpaymentTotal;
var Total = document.getElementById('total');
aluminum_qty = system_size * 4;
system_rate_input = 2.9 * 1000 * 1.2 * system_size;
Total.value = systemTotal + moduleTotal + inverterTotal+ aluminumTotal + servicedtTotal+ installationTotal + dnpaymentTotal;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script src="1.js"></script>
<form name="frm" >
<h2>Cotizacion</h2>
<table class="Cotization">
<tbody>
<tr>
<th style="width:25%;font-size:16px;text-align:center;">Description</th>
<th style="width:15%;" class="qtyhd" title="qtytt">Qty</th>
<th style="width:15%;" class="ratehd" title="ratett">Rate</th>
<th style="width:15%;" class="tlhd" title="totaltt">Total</th>
</tr>
<tr>
<td>PV Grid Tied System</td>
<td> <input id="system_qty" name="system_qty" value="1" type="number" /></td>
<td> <input id="system_rate" name="system_rate" value="0" type="number" /></td>
<td> <output id="system_total"> </output></td>
</tr>
<tr>
<td>Solar Modules 250w</td>
<td> <input id="modules_qty" name="modules_qty" value="0" type="number" /></td>
<td> <input id="modules_rate" name="modules_rate" value="0" type="number" /></td>
<td> <output id="modules_total"> </output></td>
</tr>
<tr>
<td>Inverter</td>
<td> <input id="inverter_qty" name="inverter_qty" value="1" type="number" /></td>
<td> <input id="inverter_rate" name="inverter_rate" value="0" type="number" /></td>
<td> <output id="inverter_total"> </output></td>
</tr>
<tr>
<td>Aluminum Fames</td>
<td> <input id="aluminum_qty" name="aluminum_qty" value="0" type="number" /></td>
<td> <input id="aluminum_rate" name="aluminum_rate" value="0" type="number" /></td>
<td> <output id="aluminum_total"> </output></td>
</tr>
<tr>
<td>Service Disconnect</td>
<td> <input id="servicedt_qty" name="servicedt_qty" value="1" type="number" /></td>
<td> <input id="servicedt_rate" name="servicedt_rate" value="0" type="number" /></td>
<td> <output id="servicedt_total"> </output></td>
</tr>
<tr>
<td>Installation</td>
<td> <input id="installation_qty" name="installation_qty" value="1" type="number" /></td>
<td> <input id="installation_rate" name="installation_rate" value="0" type="number" /></td>
<td> <output id="installation_total"> </output></td>
</tr>
<tr>
<td>Down Payment</td>
<td> <input id="dnpayment_qty" name="dnpayment_qty" value="-1" type="number" /></td>
<td> <input id="dnpayment_rate" name="dnpayment_rate" value="0" type="number" /></td>
<td> <output id="dnpayment_total"> </output></td>
</tr>
<tr>
<td>Total </td>
<td> </td>
<td> </td>
<td> <input value="" id="total" name="total"/></td>
</tr>
</tbody>
</table>
</form>
<button id="btn" onclick="rr()">Click</button>
</body>
</html>

Categories

Resources