Get sum of radio button value using javascript function in table - javascript

I am looking to get the sum of these 4 different values without query through a the radio buttons.
Here my javascript and html, once I click on submit, 0 appears in the total field, thank you for your help!
<!DOCTYPE html>
<html>
<body>
<script>
function checkRadio() {
var selectedAge="";
var selectedBmi="";
var selectedDiabete="";
var description="";
var len = document.row.length;
var i;
function init(){
for (i = 0; i<len; i++) {
if (document.row[i].value);
break;
}
if (selectedAge == "") {
document.getElementByid("radio_error").innnerHTML = "no option selected";
return false
}
else {
document.getElementById("radio_error").innerHTML = "";
return true;
}
}
init();
}
</script>
<script>
function addNumbers()
{
var val1 = parseInt(document.getElementById("value1").value);
var val2 = parseInt(document.getElementById("value2").value);
var val3 = parseInt(document.getElementById("value3").value);
var val4 = parseInt(document.getElementById("value4").value);
var ansD = document.getElementById("answer");
ansD.value = val1 + val2 + val3 + val4;
}
</script>
<table>
<tr>
<th scope="col"></th>
<th scope="col">noRisk</th>
<th scope="col">lowRisk</th>
<th scope="col">mediumRisk</th>
<th scope="col">HighRisk</th>
</tr>
<tr>
<th scope="row"><div class="lefttext">How old are you?</div></th>
<td><input type="radio" id="value1" name="selectedAge" onclick="addNumber(val1)" value="0"checked>1-25</td>
<td><input type="radio" id="value1" name="selectedAge" onclick="addNumber(val1)" value="5">26-40</td>
<td><input type="radio" id="value1" name="selectedAge" onclick="addNumber(val1)" value="8">41-60</td>
<td><input type="radio" id="value1" name="selectedAge" onclick="addNumber(val1)" value="10">1-25</td>
</tr>
<tr>
<th scope="row"><div class="lefttext">What is you BMI?</div></th>
<td><input type="radio" id="value2" name="selectedBmi" onclick="addNumber(val2)" value="0" checked>0-25</td>
<td><input type="radio" id="value2" name="selectedBmi" onclick="addNumber(val2)" value="0">26-30</td>
<td><input type="radio" id="value2" name="selectedBmi" onclick="addNumber(val2)" value="9">31-35</td>
<td><input type="radio" id="value2" name="selectedBmi" onclick="addNumber(val2)" value="10">35+</td>
</tr>
<tr>
<th scope="row"><div class="lefttext">Does anybody in your family have diabetes?</div></th>
<td><input type="radio" id="value3" name="selectedDiabete" onclick="addNumber(val3)" value="0" checked>No</td>
<td><input type="radio" id="value3" name="selectedDiabete" onclick="addNumber(val3)" value="7">Grandparent</td>
<td><input type="radio" id="value3" name="selectedDiabete" onclick="addNumber(val3)" value="15">Sibling</td>
<td><input type="radio" id="value3" name="selectedDiabete" onclick="addNumber(val3)" value="15">Parent</td>
</tr>
<tr>
<th scope="row"><div class="lefttext">How would you describe your diabete</div></th>
<td><input type="radio" id="value4" name="description" onclick="addNumber(val4)" value="0" checked >Low sugar</td>
<td><input type="radio" id="value4" name="description" onclick="addNumber(val4)" value="0">Normal sugar</td>
<td><input type="radio" id="value4" name="description" onclick="addNumber(val4)" value="7">Quite high sugar</td>
<td><input type="radio" id="value4" name="description" onclick="addNumber(val4)" value="10">High sugar</td>
</tr>
</table>
<input type="button" name="Sumbit" value="Submit" onclick="javascript:addNumbers()"/>
Total = <input type="text" id="answer" name="answer" value=""/>
</body>

You have to specify that you only want the value of the checked checkboxes. You now select all the checkboxes. Try this instead:
function addNumbers()
{
var val1 = parseInt(document.querySelector('input[name = "selectedAge"]:checked').value);
var val2 = parseInt(document.querySelector('input[name = "selectedBmi"]:checked').value);
var val3 = parseInt(document.querySelector('input[name = "selectedDiabete"]:checked').value);
var val4 = parseInt(document.querySelector('input[name = "description"]:checked').value);
var ansD = document.getElementById("answer");
ansD.value = val1 + val2 + val3 + val4;
}

Here is working example.
Basically:
var sum = function(a, b) {
return a + b;
};
var getPollResult = function() {
var checkedRadioButtons = document.querySelectorAll('table input[type="radio"]:checked');
return Array.prototype.map.call(checkedRadioButtons, function(radio) { return parseInt(radio.value, 10); }).reduce(sum, 0);
};
document.getElementById("submit").addEventListener('click', function() {
document.getElementById("answer").value = getPollResult();
});

Related

Button not being enabled after click on checkboxes

So, I have created a table with checkboxes and I want the user to check at least two options in order to enable the button to submit the answers.
HTML
<body>
<h1>Checked two options</h1>
<br />
<p>What are some of your favorite dishes?</p>
<table id="tblFoods">
<tr>
<td><input id="chkPizza" type="checkbox" /><label for="chkPizza">Pizza</label></td>
</tr>
<tr>
<td><input id="chkLasagna" type="checkbox" /><label for="chkLasagna">Lasagna</label></td>
</tr>
<tr>
<td><input id="chkPasta" type="checkbox" /><label for="chkPasta">Pasta</label></td>
</tr>
<tr>
<td><input id="chkBarbecue" type="checkbox" /><label for="chkBarbecue">Barbecue</label></td>
</tr>
</table>
<br />
<input type="submit" id="mybtn" disabled value="Submit" onclick="EnableButton()" />
</body>
And I have this function, but it's not working. I'm using a looping to count how many options have been checked by the user, but it doesn't work.
JS
function EnableButton() {
var tblFoods = document.getElementById("tblFoods");
var checkeds = tblFoods.getElementsByTagName("INPUT");
var counter = 0;
for (let i = 0; i < marcados.length; i++) {
if (checkeds[i].checked) {
counter++;
}
}
if (counter >= 2) {
document.getElementById("mybtn").disabled = false;
} else {
document.getElementById("mybtn").disabled = true;
}
}
What am I doing wrong?
You need to check for whether the button needs to be enabled when the inputs get checked, not when the button gets clicked.
The nicest, most concise way to do this is:
const table = document.querySelector('#tblFoods');
table.addEventListener('change', () => {
const checkedCount = [...table.querySelectorAll('input')].reduce((a, input) => a + input.checked, 0);
document.getElementById("mybtn").disabled = checkedCount < 2;
});
<h1>Checked two options</h1>
<br/>
<p>What are some of your favorite dishes?</p>
<table id="tblFoods">
<tr>
<td><input id="chkPizza" type="checkbox" /><label for="chkPizza">Pizza</label></td>
</tr>
<tr>
<td><input id="chkLasagna" type="checkbox" /><label for="chkLasagna">Lasagna</label></td>
</tr>
<tr>
<td><input id="chkPasta" type="checkbox" /><label for="chkPasta">Pasta</label></td>
</tr>
<tr>
<td><input id="chkBarbecue" type="checkbox" /><label for="chkBarbecue">Barbecue</label></td>
</tr>
</table>
<br />
<input type="submit" id="mybtn" disabled value="Submit" />
Your original code, tweaked, works too, but is pretty verbose in comparison.
document.querySelector('#tblFoods').addEventListener('change', () => {
var tblFoods = document.getElementById("tblFoods");
var checkeds = tblFoods.getElementsByTagName("INPUT");
var counter = 0;
for(let i =0; i < checkeds.length;i++)
{
if(checkeds[i].checked)
{
counter++;
}
}
if(counter>=2)
{
document.getElementById("mybtn").disabled = false;
}
else
{
document.getElementById("mybtn").disabled = true;
}
});
<h1>Checked two options</h1>
<br/>
<p>What are some of your favorite dishes?</p>
<table id="tblFoods">
<tr>
<td><input id="chkPizza" type="checkbox" /><label for="chkPizza">Pizza</label></td>
</tr>
<tr>
<td><input id="chkLasagna" type="checkbox" /><label for="chkLasagna">Lasagna</label></td>
</tr>
<tr>
<td><input id="chkPasta" type="checkbox" /><label for="chkPasta">Pasta</label></td>
</tr>
<tr>
<td><input id="chkBarbecue" type="checkbox" /><label for="chkBarbecue">Barbecue</label></td>
</tr>
</table>
<br />
<input type="submit" id="mybtn" disabled value="Submit" />
You have to handle the changes on each checkbox element separately and finally, the submit button. You can do something like the below.
Note: See how the onClick event handlers are used on each input type checkbox element and on the submit button separately. Also, we have to reset everything when submitting.
A possible solution:
let checks_counter = 0;
function EnableButton(checkbox) {
if (checkbox.checked) {
checks_counter++;
}
if (checks_counter > 2) {
document.getElementById("mybtn").disabled = false;
} else {
document.getElementById("mybtn").disabled = true;
}
}
function submitHandler() {
var elements = document.getElementsByTagName('input');
//unchecking everything
for (var i = elements.length; i--;) {
if (elements[i].type == 'checkbox') {
elements[i].checked = false;
}
}
//resetting the counter and disabling the button
checks_counter = 0;
document.getElementById("mybtn").disabled = true;
}
<body>
<h1>Checked two options</h1>
<br/>
<p>What are some of your favorite dishes?</p>
<table id="tblFoods">
<tr>
<td><input id="chkPizza" type="checkbox" onChange="EnableButton(this)" /><label for="chkPizza">Pizza</label></td>
</tr>
<tr>
<td><input id="chkLasagna" type="checkbox" onChange="EnableButton(this)" /><label for="chkLasagna">Lasagna</label></td>
</tr>
<tr>
<td><input id="chkPasta" type="checkbox" onChange="EnableButton(this)" /><label for="chkPasta">Pasta</label></td>
</tr>
<tr>
<td><input id="chkBarbecue" type="checkbox" onChange="EnableButton(this)" /><label for="chkBarbecue">Barbecue</label></td>
</tr>
</table>
<br />
<input type="submit" id="mybtn" disabled value="Submit" onclick="submitHandler()" />
</body>
You need to call your Enable function when you check boxes. Here's a working example: https://codesandbox.io/s/proud-architecture-ou5l2?file=/src/index.js
using your existing code:
var tblFoods = document.getElementById("tblFoods");
var checkeds = tblFoods.querySelectorAll("input");
const btn = document.getElementById("mybtn");
function enableButton() {
var counter = 0;
for (let i = 0; i < checkeds.length; i++) {
if (checkeds[i].checked) {
counter++;
}
}
if (counter >= 2) {
btn.disabled = false;
} else {
btn.disabled = true;
}
}
const handleClick = () => {
enableButton();
// do whatever else you need in here
};
checkeds.forEach((box) => box.addEventListener("click", handleClick));
You have to run your function when the user select the food, not when the user click the button. A simple solution is removing the onclick event from the button and adding the onchange event in every input:
<h1>Checked two options</h1>
<br />
<p>What are some of your favorite dishes?</p>
<table id="tblFoods">
<tr>
<td><input id="chkPizza" type="checkbox" onchange="EnableButton()" /><label for="chkPizza">Pizza</label></td>
</tr>
<tr>
<td><input id="chkLasagna" type="checkbox" onchange="EnableButton()" /><label for="chkLasagna">Lasagna</label>
</td>
</tr>
<tr>
<td><input id="chkPasta" type="checkbox" onchange="EnableButton()" /><label for="chkPasta">Pasta</label></td>
</tr>
<tr>
<td><input id="chkBarbecue" type="checkbox" onchange="EnableButton()" /><label for="chkBarbecue">Barbecue</label>
</td>
</tr>
</table>
<br />
<input type="submit" id="mybtn" disabled value="Submit" />
You could use something like:
document.querySelectorAll("input[type='checkbox']").forEach(e => e.addEventListener("click", () => {
const submitButton = document.querySelector("#mybtn");
if (!submitButton) return;
const checkedInputs = document.querySelectorAll("#tblFoods input[type='checkbox']:checked").length;
submitButton.disabled = checkedInputs < 2;
}));
In other words, every time a checkbox is clicked, a check is run on how many checkboxes are checked in total. If this amount is greater than or equal to two, the button is enabled, otherwise it is disabled.
Maybe i am wrong but since u had initialized counter = 0, every time that the function its called, it will automatically set to 0, so u should declare it globally in order to be an effective counter.
var counter = 0;
function EnableButton()
{
var tblFoods = document.getElementById("tblFoods");
var checkeds = tblFoods.getElementsByTagName("INPUT");
for(let i =0; i < checkeds.length;i++)
{
if(checkeds[i].checked)
{
counter++;
}
}
if(counter>=2)
{
document.getElementById("mybtn").disabled = false;
}
else
{
document.getElementById("mybtn").disabled = true;
}
}

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>

Need help getting fields to Populate using Javascript

I am taking an introduction course to HTML and have been struggling to find my error with a page that uses java. I am sure I am making a simple mistake but I am not seeing it
Here is the fiddle of the code I am working with:
https://jsfiddle.net/Terranova1340/ctc66nmu/2/
<body onload="processForm()">
<div id="wrapper">
<form id="cars" method="get">
<h1>AutoMart Sales Order Form</h1>
<img id="imgCar" src="civic2.jpg" />
<table class="Controls">
<tr>
<td><label for="Model">Select a Model:</label><br></td>
<td><select id="selModel" onchange="chgImage()">
<option value="civic" >Civic</option>
<option value="accord" >Accord</option>
</select></td>
</tr>
<tr>
<td><label for="optAcces">Optional Accessories:</label><br></td>
<td><label class='checkbox'><input type="checkbox" id="optAcces1"value="stereoSys" onchange="processForm()"> Stereo System<br>
<label class='checkbox'><input type="checkbox" id="optAcces2" value="leatherInt" onchange="processForm()"> Leather Interiors<br>
<label class='checkbox'><input type="checkbox" id="optAcces3" value="gpsSys" onchange="processForm()"> GPS System<br><br>
</td>
</tr>
<tr>
</tr>
<tr>
<tr>
</tr>
<td><label for="extFin">Exterior Finish:</label><br></td>
<td><label class='radiolabel'><input type="radio" name="selectedfinish" id="stanFin" onchange="processForm()"> Standard Finish<br>
<label class='radiolabel'><input type="radio" name="selectedfinish" id="metalFin" onchange="processForm()"> Metalic Finish<br>
<label class='radiolabel'><input type="radio" name="selectedfinish" id="custFin" onchange="processForm()"> Customized Finish<br>
</td>
</tr>
<tr>
<td><label for="base">Base Price</label><br></td>
<td><input type="text" id="basePrice" style="text-align:right;" readonly><br></td>
</tr>
<tr>
<td><label for="access">Accessories Price</label><br></td>
<td><input type="text" id="accessPrice" style="text-align:right;" readonly><br></td>
</tr>
<tr>
<td><label for="extPrice">Exterior Finish Price</label><br></td>
<td><input type="text" id="extPrice" style="text-align:right;" readonly><br></td>
</tr>
<tr>
<td><label>Estimated Total Price</label><br></td>
<td><input class- "ReadOnlyControls" type="text" name="estPrice" id="estPrice" style="text-align:right;" readonly><br></td>
</tr>
</table>
<input class="buttons" type="reset" value="Clear">
<input class="buttons" type="button" onclick="window.print()"; value="Print Form" id="print">
</form>
</div>
</body>
</html>
Java is
function chgImage() {
if (document.getElementById("selModel").value =="civic")
{
document.getElementById("imgCar").src="Civic2.jpg";
}
else
{
document.getElementById("imgCar").src="Accord2.jpg";
}
processForm();
}
function processForm(){
var bPrice = 0;
var aPrice = 0;
var oPrice = 0;
var tPrice = 0;
if (document.getElementById("selModel").value =="civic")
{
bPrice = 17355.89;
if (document.getElementById("optAccess1").checked == true)
{
aPrice = aPrice + 400.22;
}
if (document.getElementById("optAccess2").checked == true)
{
aPrice = aPrice + 850.44;
}
if (document.getElementById("optAccess3").checked == true)
{
aPrice = aPrice + 1600.00;
}
if (document.getElementById("metalFin").checked == true)
{
oPrice = 305.72;
}
if (document.getElementById("custFin").checked == true)
{
oPrice = 350.00;
}
}
else
{
basePrice = 19856.79;
if (document.getElementById("optAccess1").checked == true)
{
aPrice = aPrice + 500.89;
}
if (document.getElementById("optAccess2").checked == true)
{
aPrice = aPrice + 1015.85;
}
if (document.getElementById("optAccess3").checked == true)
{
aPrice = aPrice + 1600.00;
}
if (document.getElementById("metalFin").checked == true)
{
oPrice = 385.67;
}
if (document.getElementById("custFin").checked == true)
{
oPrice = 400.00;
}
}
//calculate total
tPrice = bPrice+aPrice+oPrice;
document.getElementById("basePrice").value = "$" + formatCurrency(bPrice).toString();
document.getElementById("accessPrice").value = "$" + formatCurrency(aPrice).toString();
document.getElementById("extPrice").value = "$" + formatCurrency(oPrice).toString();
document.getElementById("estPrice").value = "$" + formatCurrency(tPrice).toString();
}
function formatCurrency(num){
num = isNaN(num) || num === ''|| num === null ? 0.00 : num;
return parseFloat(num).toFixed(2);
}
My issue is the Base Price to Estimated Total Price fields aren't populating.
Thanks in advance!
function chgImage() {
if (document.getElementById("selModel").value =="civic")
{
document.getElementById("imgCar").src="Civic2.jpg";
}
else
{
document.getElementById("imgCar").src="Accord2.jpg";
}
processForm();
}
function processForm(){
var bPrice = 0;
var aPrice = 0;
var oPrice = 0;
var tPrice = 0;
if (document.getElementById("selModel").value =="civic")
{
bPrice = 17355.89;
if (document.getElementById("optAccess1").checked == true)
{
aPrice = aPrice + 400.22;
}
if (document.getElementById("optAccess2").checked == true)
{
aPrice = aPrice + 850.44;
}
if (document.getElementById("optAccess3").checked == true)
{
aPrice = aPrice + 1600.00;
}
if (document.getElementById("metalFin").checked == true)
{
oPrice = 305.72;
}
if (document.getElementById("custFin").checked == true)
{
oPrice = 350.00;
}
}
else
{
basePrice = 19856.79;
if (document.getElementById("optAccess1").checked == true)
{
aPrice = aPrice + 500.89;
}
if (document.getElementById("optAccess2").checked == true)
{
aPrice = aPrice + 1015.85;
}
if (document.getElementById("optAccess3").checked == true)
{
aPrice = aPrice + 1600.00;
}
if (document.getElementById("metalFin").checked == true)
{
oPrice = 385.67;
}
if (document.getElementById("custFin").checked == true)
{
oPrice = 400.00;
}
}
//calculate total
tPrice = bPrice+aPrice+oPrice;
document.getElementById("basePrice").value = "$" + formatCurrency(bPrice).toString();
document.getElementById("accessPrice").value = "$" + formatCurrency(aPrice).toString();
document.getElementById("extPrice").value = "$" + formatCurrency(oPrice).toString();
document.getElementById("estPrice").value = "$" + formatCurrency(tPrice).toString();
}
function formatCurrency(num){
num = isNaN(num) || num === ''|| num === null ? 0.00 : num;
return parseFloat(num).toFixed(2);
}
<body onload="processForm()">
<div id="wrapper">
<form id="cars" method="get">
<h1>AutoMart Sales Order Form</h1>
<img id="imgCar" src="civic2.jpg" />
<table class="Controls">
<tr>
<td><label for="Model">Select a Model:</label><br></td>
<td><select id="selModel" onchange="chgImage()">
<option value="civic" >Civic</option>
<option value="accord" >Accord</option>
</select></td>
</tr>
<tr>
<td><label for="optAcces">Optional Accessories:</label><br></td>
<td><label class='checkbox'><input type="checkbox" id="optAccess1"value="stereoSys" onchange="processForm()"> Stereo System<br>
<label class='checkbox'><input type="checkbox" id="optAccess2" value="leatherInt" onchange="processForm()"> Leather Interiors<br>
<label class='checkbox'><input type="checkbox" id="optAccess3" value="gpsSys" onchange="processForm()"> GPS System<br><br>
</td>
</tr>
<tr>
</tr>
<tr>
<tr>
</tr>
<td><label for="extFin">Exterior Finish:</label><br></td>
<td><label class='radiolabel'><input type="radio" name="selectedfinish" id="stanFin" onchange="processForm()"> Standard Finish<br>
<label class='radiolabel'><input type="radio" name="selectedfinish" id="metalFin" onchange="processForm()"> Metalic Finish<br>
<label class='radiolabel'><input type="radio" name="selectedfinish" id="custFin" onchange="processForm()"> Customized Finish<br>
</td>
</tr>
<tr>
<td><label for="base">Base Price</label><br></td>
<td><input type="text" id="basePrice" style="text-align:right;" readonly><br></td>
</tr>
<tr>
<td><label for="access">Accessories Price</label><br></td>
<td><input type="text" id="accessPrice" style="text-align:right;" readonly><br></td>
</tr>
<tr>
<td><label for="extPrice">Exterior Finish Price</label><br></td>
<td><input type="text" id="extPrice" style="text-align:right;" readonly><br></td>
</tr>
<tr>
<td><label>Estimated Total Price</label><br></td>
<td><input class- "ReadOnlyControls" type="text" name="estPrice" id="estPrice" style="text-align:right;" readonly><br></td>
</tr>
</table>
<input class="buttons" type="reset" value="Clear">
<input class="buttons" type="button" onclick="window.print()"; value="Print Form" id="print">
</form>
</div>
</body>
</html>
You are using wrong id's, change to optAccess1,optAccess2,optAccess3 here
<td><label class='checkbox'><input type="checkbox" id="optAccess1"value="stereoSys" onchange="processForm()"> Stereo System<br>
<label class='checkbox'><input type="checkbox" id="optAccess2" value="leatherInt" onchange="processForm()"> Leather Interiors<br>
<label class='checkbox'><input type="checkbox" id="optAccess3" value="gpsSys" onchange="processForm()"> GPS System<br><br>
</td>

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>

Cannot Loop Through Rows of a Table in Javascript or Jquery

There are lots of examples on the internet, including SO, telling people how to loop through the rows of a table and get the values using Javascript or Jquery. Unfortunately, none of these examples work for me:
JavaScript:
var table = document.getElementById("tbInvoiceDetails");
var rowLength = table.rows.length;
for (var i = 0; i < rowLength; i += 1) {
var row = table.rows[i];
var cell = row.cells[10].innerHTML;
}
This gets:
<input id="InvoiceDetails_0__Title" name="InvoiceDetails[0].Vat" value="0" type="hidden">0
How can I get the value (=0) from this?
JQuery:
$("#tbInvoiceDetails tr").each(function () {
//Code
}
This simply does not work. I have tried every combination I can think of inside the "" and nothing works.
Table HTML with One Line:
<tbody id="tbInvoiceDetails">
<tr id="trInvoiceDetail0">
<td style="display:none">
<input name="InvoiceDetails.Index" value="0" type="hidden"></td>
<td style="display:none"><input name="InvoiceDetails[0].id" value="-1" type="hidden"></td>
<td style="display:none"><input name="InvoiceDetails[0].InvoiceId" value="0" type="hidden"></td>
<td><input id="InvoiceDetails_0__Title" name="InvoiceDetails[0].LineTypeId" value="1" type="hidden">1</td>
<td><input id="InvoiceDetails_0__Title" name="InvoiceDetails[0].AllocationCodeId" value="19" type="hidden">2030 6016750 KQ73020394 11014008</td>
<td><input id="InvoiceDetails_0__Title" name="InvoiceDetails[0].GspId" value="" type="hidden"></td>
<td><input id="InvoiceDetails_0__Title" name="InvoiceDetails[0].RunTypeId" value="" type="hidden"></td>
<td><input id="InvoiceDetails_0__Title" name="InvoiceDetails[0].BillingPeriodFromDate" value="06/08/2015" type="hidden">06/08/2015</td>
<td><input id="InvoiceDetails_0__Title" name="InvoiceDetails[0].BillingPeriodToDate" value="19/08/2015" type="hidden">19/08/2015</td>
<td><input id="InvoiceDetails_0__Title" name="InvoiceDetails[0].Net" value="9999" type="hidden">9999</td>
<td><input id="InvoiceDetails_0__Title" name="InvoiceDetails[0].Vat" value="0" type="hidden">0</td>
<td><input id="InvoiceDetails_0__Title" name="InvoiceDetails[0].InterestPay" value="0" type="hidden">0</td>
<td><input id="InvoiceDetails_0__Title" name="InvoiceDetails[0].InterestReceiveable" value="0" type="hidden">0</td>
<td><input id="InvoiceDetails_0__Title" name="InvoiceDetails[0].VatCodeId" value="8" type="hidden">8</td>
<td><input class="btn" id="btnRemoveInvoiceDetail" value="Remove" onclick="removeRow(0);" type="button"></td>
</tr>
</tbody>
Going the by-column-position route:
jQuery:
$('#tbInvoiceDetails tr td:nth-child(11) input').each(
function() {
var val = this.value;
console.log(val);
}
);
Pure JS:
var table = document.getElementById("tbInvoiceDetails");
var rowLength = table.rows.length;
for (var i = 0; i < rowLength; i += 1) {
var input = table.rows[i].cells[10].firstElementChild;
var val = input.value;
console.log(val);
}

Categories

Resources