Javascript update multiple form totals from checked boxes - javascript

I have a form with various items with checkboxes and those items may be repeated multiple times. I'd like to have another table or form that shows all those items and has a running total for the number of items that are checked and it updates as they are checked.
Let's say I've got the initial form like this:
<form name="myform">
<input type="checkbox" name="model1" value="2">2 x model1
<input type="checkbox" name="model2" value="2">2 x model2
<input type="checkbox" name="model3" value="2">2 x model3
<input type="checkbox" name="model1" value="1">1 x model1
<input type="checkbox" name="model1" value="4">4 x model1
<input type="checkbox" name="model3" value="5">5 x model3
<p>
Totals: <br>
<input type="text" name="totalmodel1" value="0" size="2"><br>
<input type="text" name="totalmodel2" value="0" size="2"><br>
<input type="text" name="totalmodel3" value="0" size="2"><br>
</form>
How can I get the totals to update as the items are checked off. I've used javascript to update lots of other stuff like this and I've found examples that will add up my choices if they are all to be added together, but I haven't been able to successfully make it work with adding multiple items separately.
Any and all help is appreciated.

I made a JS Fiddle as an example of where to start... Here
Basically what I did was:
Relate the input text to checkboxes:
var modelNum = ($(this).attr("name")).slice(($(this).attr("name").length) - 1, $(this).attr("name").length);
var child = "totalmodel" + modelNum;
Make input text only appear if related checkbox is checked:
if (this.checked) {
$("input").each(function() {
if ($(this).attr("name") == child) {
$(this).show();
}
});
} else {
$("input").each(function() {
if ($(this).attr("name") == child) {
$(this).hide();
}
});
}
And show you how to get the value of text (assuming user will enter integer):
$("input").each(function(){ //This is how you get the value of each...
if($(this).is(":text")){
var value = $(this).attr("value");
}
});

So I had previously found an example at http://www.madirish.net/11 that did what I wanted but it was only for one item to total up. I needed to total multiple items separately. I had been trying to modify his code to my needs and it wasn't working, but then I realized his code wouldn't work when I pasted it into jsfiddle. So I tried it on my own server and it worked. I gave up on jsfiddle (I'm sure it's my fault somehow that it didn't work) and began testing on my own server. Here's an example output of what I did to get it to work (please ignore the ugly layout...I didn't need it to be pretty while testing).
<script type="text/javascript">
function checkTotal1() {
document.listForm.total1.value = '';
var sum = 0;
if (document.getElementsByName("choice1").length == 1) {
if (document.listForm.choice1.checked) {
sum = sum + parseInt(document.listForm.choice1.value);
}
} else {
for (i=0;i<document.listForm.choice1.length;i++) {
if (document.listForm.choice1[i].checked) {
sum = sum + parseInt(document.listForm.choice1[i].value);
}
}
}
document.listForm.total1.value = sum;
}
function checkTotal2() {
document.listForm.total2.value = '';
var sum = 0;
if (document.getElementsByName("choice2").length == 1) {
if (document.listForm.choice2.checked) {
sum = sum + parseInt(document.listForm.choice2.value);
}
} else {
for (i=0;i<document.listForm.choice2.length;i++) {
if (document.listForm.choice2[i].checked) {
sum = sum + parseInt(document.listForm.choice2[i].value);
}
}
}
document.listForm.total2.value = sum;
}
function checkTotal3() {
document.listForm.total3.value = '';
var sum = 0;
if (document.getElementsByName("choice3").length == 1) {
if (document.listForm.choice3.checked) {
sum = sum + parseInt(document.listForm.choice3.value);
}
} else {
for (i=0;i<document.listForm.choice3.length;i++) {
if (document.listForm.choice3[i].checked) {
sum = sum + parseInt(document.listForm.choice3[i].value);
}
}
}
document.listForm.total3.value = sum;
}
function checkTotal4() {
document.listForm.total4.value = '';
var sum = 0;
if (document.getElementsByName("choice4").length == 1) {
if (document.listForm.choice4.checked) {
sum = sum + parseInt(document.listForm.choice4.value);
}
} else {
for (i=0;i<document.listForm.choice4.length;i++) {
if (document.listForm.choice4[i].checked) {
sum = sum + parseInt(document.listForm.choice4[i].value);
}
}
}
document.listForm.total4.value = sum;
}
function checkTotal5() {
document.listForm.total5.value = '';
var sum = 0;
if (document.getElementsByName("choice5").length == 1) {
if (document.listForm.choice5.checked) {
sum = sum + parseInt(document.listForm.choice5.value);
}
} else {
for (i=0;i<document.listForm.choice5.length;i++) {
if (document.listForm.choice5[i].checked) {
sum = sum + parseInt(document.listForm.choice5[i].value);
}
}
}
document.listForm.total5.value = sum;
}
</script>
<form name="listForm">
<table>
<tr>
<td align="left" valign="top">
<input type="checkbox" name="choice1" value="1" onchange="checkTotal1()">1 x mod1<br>
<input type="checkbox" name="choice1" value="1" onchange="checkTotal1()">1 x mod1<br>
<input type="checkbox" name="choice2" value="2" onchange="checkTotal2()">2 x mod2<br>
<input type="checkbox" name="choice2" value="2" onchange="checkTotal2()">2 x mod2<br>
<input type="checkbox" name="choice3" value="1" onchange="checkTotal3()">1 x mod3<br>
<input type="checkbox" name="choice3" value="1" onchange="checkTotal3()">1 x mod3<br>
<input type="checkbox" name="choice3" value="1" onchange="checkTotal3()">1 x mod3<br>
<input type="checkbox" name="choice4" value="1" onchange="checkTotal4()">1 x mod4<br>
<input type="checkbox" name="choice5" value="1" onchange="checkTotal5()">1 x mod5<br>
<input type="checkbox" name="choice5" value="1" onchange="checkTotal5()">1 x mod5<br>
</td>
<td align="left" valign="top">
<table>
<tr>
<th>Product Model</th>
<th>Qty Received</th>
<th>Qty Checked</th>
</tr>
<tr>
<td>mod1</td>
<td align="right">2</td>
<td><input type="text" size="3" name="total1" value="0"></td>
</tr>
<tr>
<td>mod2</td>
<td align="right">4</td>
<td><input type="text" size="3" name="total2" value="0"></td>
</tr>
<tr>
<td>mod3</td>
<td align="right">3</td>
<td><input type="text" size="3" name="total3" value="0"></td>
</tr>
<tr>
<td>mod4</td>
<td align="right">1</td>
<td><input type="text" size="3" name="total4" value="0"></td>
</tr>
<tr>
<td>mod5</td>
<td align="right">2</td>
<td><input type="text" size="3" name="total5" value="0"></td>
</tr>
</table>
</td>
</tr>
</table>
</form>

Related

How do I check 1 checkbox or radial button as N/A and make all the items in the same table also get checked N/A automatically?

I have a simple table with 4 columns.
A row label and 1 column for PASS, FAIL AND N/A.
I have it so each row only allows 1 selection which seems to be working fine.
My header row only has N/A. I want it so if I check N/A in my header row all other rows below in the same table will also be marked N/A automatically.
I'm a novice to HTML and scripts FYI :(
Any help you can provide would be greatly appreciated!
This is what I tried.
<table>
<tr>
<TD><label>HEADING:</label> </td>
<TD><label></label></td>
<TD> </td>
<TD> </td>
<TD><label></label></td>
<TD> </td>
<TD><label>N/A</label></td>
<TD><input type="checkbox" name="HEADING1"id="is_HEADING1"/></td>
</tr>
<tr>
<TD><label>Q1:</label> </td>
<TD><label>PASS</label></td>
<TD><input type="radio" name="Q1" id="is_PASS" /></td>
<TD> </td>
<TD><label>FAIL</label></td>
<TD><input type="radio" name="Q1" id="is_FAIL" /></td>
<TD><label>N/A</label></td>
<TD><input type="radio" name="Q1" id="is_N/A" /></td>
</tr>
<tr>
<TD><label>Q2:</label> </td>
<TD><label>PASS</label></td>
<TD><input type="radio" name="Q2" id="is_PASS" /></td>
<TD> </td>
<TD><label>FAIL</label></td>
<TD><input type="radio" name="Q2" id="is_FAIL" /></td>
<TD><label>N/A</label></td>
<TD><input type="radio" name="Q2" id="is_N/A" /></td>
</tr>
</table>
<script>
function valueChanged() {
if (document.getElementByid("is_PASS").checked == true) {
document.getElementById("is_FAIL").value = 1;
document.getElementById("is_N/A").value = 0;
} else {
document.getElementById("is_PASS").value = 0;
document.getElementById("is_FAIL").value = 1;
document.getElementById("is_N/A").value = 1;
}
console.log(document.getElementById("is_PASS").value);
console.log(document.getElementById("is_FAIL").value)
console.log(document.getElementById("is_N/A").value)
}
<script>
function valueChanged() {
if (document.getElementByNameId("is_PASS").checked == true) {
document.getElementById("is_FAIL").value = 1;
document.getElementById("is_N/A").value = 0;
} else {
document.getElementById("is_PASS").value = 0;
document.getElementById("is_FAIL").value = 1;
document.getElementById("is_N/A").value = 1;
}
console.log(document.getElementById("is_PASS").value);
console.log(document.getElementById("is_FAIL").value)
console.log(document.getElementById("is_N/A").value)
}
</script>
I believe I need an if then else scenario that will state
if (document.getElementByid("is_HEADING1").checked == true) {
NAME "Q1" ID"N/A".VALUE = 0
NAME "Q2" ID"N/A".VALUE = 0
: } else {
:}
:<script>
I just don't know the correct syntax to reference an element Name and ID

Javascript getElementsByTagName("input").value not returning results

We have one page with process and matched subprocess listed based dynamically based on process selection. Process can have more than one selection. Based on process selection sub process will be loaded.
Here I need to validate max only one subprocess needs to be selected for each process.
I am trying to achieve that with below validation. Not getting values on checkboxProcess[i].value() tried with InnerText and also InnerHtml
function Validate() {
var atLeast = 1;
var CHKcblProcess = document.getElementById("cblProcess");
var checkboxProcess = CHKcblProcess.getElementsByTagName("input");
//var listOfSpans = checkboxProcess.getElementsByTagName('span');
var counter = 0;
var subcounter = 0;
for (var i = 0; i < checkboxProcess.length; i++) {
if (checkboxProcess[i].checked) {
counter++;
}
}
if (atLeast > counter) {
alert("Please select atleast " + atLeast + " Process item(s)");
return false;
} else {
var CHKcblSubProcess = document.getElementById("cblSubDept");
var checkboxSubProcess = CHKcblSubProcess.getElementsByTagName("input");
var subcounter = 0;
for (var i = 0; i < checkboxProcess.length; i++) {
if (checkboxProcess[i].checked) {
alert(checkboxProcess[i].innerText);
counter++;
}
}
/*for (var i = 0; i < checkboxProcess.length; i++) {
if (checkboxProcess[i].checked) {
alert(checkboxProcess[i].value());
counter++;
for (var i = 0; i < checkboxSubProcess.length; i++) {
if (checkboxSubProcess[i].checked) {
subcounter++;
}
}
}
}*/
return true;
}
}
<table id="cblProcess" border="0" style="font-size:X-Small;">
<tr>
<td><input id="cblProcess_0" type="checkbox" name="cblProcess$0" onclick="javascript:setTimeout('__doPostBack(\'cblProcess$0\',\'\')', 0)" /><label for="cblProcess_0">Additive Manufacturing</label></td>
<td><input id="cblProcess_1" type="checkbox" name="cblProcess$1" checked="checked" onclick="javascript:setTimeout('__doPostBack(\'cblProcess$1\',\'\')', 0)" /><label for="cblProcess_1">Assembly</label></td>
<td><input id="cblProcess_2" type="checkbox" name="cblProcess$2" onclick="javascript:setTimeout('__doPostBack(\'cblProcess$2\',\'\')', 0)" /><label for="cblProcess_2">Component M/C</label></td>
<td><input id="cblProcess_3" type="checkbox" name="cblProcess$3" onclick="javascript:setTimeout('__doPostBack(\'cblProcess$3\',\'\')', 0)" /><label for="cblProcess_3">Compounding Extrusion Finishing</label></td>
</tr>
<tr>
<td><input id="cblProcess_4" type="checkbox" name="cblProcess$4" onclick="javascript:setTimeout('__doPostBack(\'cblProcess$4\',\'\')', 0)" /><label for="cblProcess_4">Custom Tool M/C</label></td>
<td><input id="cblProcess_5" type="checkbox" name="cblProcess$5" onclick="javascript:setTimeout('__doPostBack(\'cblProcess$5\',\'\')', 0)" /><label for="cblProcess_5">Digital Factory</label></td>
<td><input id="cblProcess_6" type="checkbox" name="cblProcess$6" onclick="javascript:setTimeout('__doPostBack(\'cblProcess$6\',\'\')', 0)" /><label for="cblProcess_6">Energy</label></td>
<td><input id="cblProcess_7" type="checkbox" name="cblProcess$7" onclick="javascript:setTimeout('__doPostBack(\'cblProcess$7\',\'\')', 0)" /><label for="cblProcess_7">Molding</label></td>
</tr>
<tr>
<td><input id="cblProcess_8" type="checkbox" name="cblProcess$8" onclick="javascript:setTimeout('__doPostBack(\'cblProcess$8\',\'\')', 0)" /><label for="cblProcess_8">Plating</label></td>
<td><input id="cblProcess_9" type="checkbox" name="cblProcess$9" onclick="javascript:setTimeout('__doPostBack(\'cblProcess$9\',\'\')', 0)" /><label for="cblProcess_9">Stamping</label></td>
<td></td>
<td></td>
</tr>
</table>
<table id="cblSubDept" border="0" style="font-size:X-Small;">
<tr>
<td><input id="cblSubDept_0" type="checkbox" name="cblSubDept$0" /><label for="cblSubDept_0">[Assembly] - Connector Assembly</label></td>
<td><input id="cblSubDept_1" type="checkbox" name="cblSubDept$1" /><label for="cblSubDept_1">[Assembly] - PSP</label></td>
<td><input id="cblSubDept_2" type="checkbox" name="cblSubDept$2" /><label for="cblSubDept_2">[No Sub-Dept]</label></td>
</tr>
</table>
<input type="submit" name="btnInquiry" value="Submit" onclick="return Validate(); id=" btnInquiry " class="NavButton-medium " />
You can use
getElementsByTagName("input")[0].value; instead of getElementsByTagName("input");
For Example
Try it
<input type="text"/>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
alert(document.getElementsByTagName("input")[0].value);
}
</script>

When non of the options are selected for the checkboxes, how to make the value none?

I've my code below and I'm using an array here. I'm trying to print "None" value when none of the options are selected, but instead when I submit the form I have a few checkboxes selected; it still says "None". Without the else if condition when I choose to not select one of the option, then I get nothing for the result.
I'm not supposed to create a "None" option for the input function.
function calculatePrice() {
var array = [];
var extras = document.calc.extras;
for (count = 0; count < extras.length; count++) {
if (extras[count].checked == true) {
array.push(extras[count].value);
} else if (!extras[count].checked) {
array = ["None"];
}
}
alert("(Including extras: " + array + ")");
}
<form name="calc">
<table>
<tr>
<td colspan="40" id="col">
<label for="extras">EXTRAS</label>
<div class="left">
<input type="checkbox" name="extras" id="ac" value="A/C">A/C (+$10)
<input type="checkbox" name="extras" id="work" value="Working Brakes">Working Brakes (+$100)<br>
<input type="checkbox" name="extras" id="cruise" value="Cruise Control">Cruise control (+$20)
<input type="checkbox" name="extras" id="seat" value="Baby Seat">Baby Seat (+$30)<br>
</div>
</td>
</tr>
<tr>
<td colspan="40" id="col">
<input type="submit" onClick="calculatePrice();" value="Estimate Cost">
</td>
</tr>
</table>
</form>
The problem is that you're replacing array with ["None"] every time there's an empty checkbox, not if all of the checkboxes are empty.
The simplest fix is to check after the loop if array is empty, e.g.:
for (count = 0; count < extras.length; count++) {
if (extras[count].checked == true) {
array.push(extras[count].value);
}
}
if (array.length === 0) {
array = ["None"];
}
Here it is in a working snippet:
function calculatePrice() {
var array = [];
var extras = document.calc.extras;
for (count = 0; count < extras.length; count++) {
if (extras[count].checked == true) {
array.push(extras[count].value);
}
}
if (array.length === 0) {
array = ["None"];
}
alert("(Including extras: " + array + ")");
}
<form name="calc">
<table>
<tr>
<td colspan="40" id="col">
<label for="extras">EXTRAS</label>
<div class="left">
<input type="checkbox" name="extras" id="ac" value="A/C">A/C (+$10)
<input type="checkbox" name="extras" id="work" value="Working Brakes">Working Brakes (+$100)<br>
<input type="checkbox" name="extras" id="cruise" value="Cruise Control">Cruise control (+$20)
<input type="checkbox" name="extras" id="seat" value="Baby Seat">Baby Seat (+$30)<br>
</div>
</td>
</tr>
<tr>
<td colspan="40" id="col">
<input type="submit" onClick="calculatePrice();" value="Estimate Cost">
</td>
</tr>
</table>
</form>

PHP - Validation radio buttons alert

i have three radio buttons input within a form. i want alert box appears when user click submit without choose or answer all questions ..
this is my form ..
<tr>
<th> Your attendance<font size="4" > </font></th>
<td> <input type="radio" name ="v1" value = "4" onclick="updateTotal();"/></td>
<td> <input type="radio" name ="v1" value = "3" onclick="updateTotal();" /></td>
<td> <input type="radio" name ="v1" value = "2" onclick="updateTotal();" /></td>
<td> <input type="radio" name ="v1" value = "1" onclick="updateTotal();" /></td>
</tr>
<tr>
<th > Your grades <font size="4" > </font></th>
<td> <input type="radio" name ="v2" value = "4" onclick="updateTotal();" /></td>
<td> <input type="radio" name ="v2" value = "3" onclick="updateTotal();" /></td>
<td> <input type="radio" name ="v2" value = "2" onclick="updateTotal();" /></td>
<td> <input type="radio" name ="v2" value = "1" onclick="updateTotal();" /></td>
</tr>
<tr>
<th >Your self-control <font size="4" > </font></th>
<td> <input type="radio" name ="v3" value = "4" onclick="updateTotal();" /></td>
<td> <input type="radio" name ="v3" value = "3" onclick="updateTotal();" /></td>
<td> <input type="radio" name ="v3" value = "2" onclick="updateTotal();" /></td>
<td> <input type="radio" name ="v3" value = "1" onclick="updateTotal();" /></td>
</tr>
i have tried this javascript code .. but it doesn't work no alert appears
<script type="text/javascript">
function validateform()
{
if(document.getElementsByName('v1').value="")
{
alert('Your grades is not selected');
return false;
}
}
</script>
Take this function, you can't use document.getElementsByName('v1').value on a radio group.
Check out this fiddle: http://jsfiddle.net/JXajh/2/
function isOneChecked(name)
{
var buttons = document.getElementsByName(name);
for (var i = 0; i < buttons.length; i++)
{
if (buttons[i].checked)
{
return true;
}
}
return false;
}
That is because the getElementsByName() will return an array of DOM elements, you can't get value or detect if an element is checked directly from this array. You must iterate through all elements check that at least one is checked. So something like this:
function validateForm() {
var radiosToValidate = ['v1', 'v2', 'v3'];
var invalidRadios = [];
for (i = 0; i < radiosToValidate.length; i++) {
var currentRadioArray = documentGetElementsByName(radiosToValidate[i]);
var currentRadioIsValid = false;
for (j = 0; j < currentRadioArray.length; j++) {
if (currentRadioArray[j].checked) {
currentRadioIsValid = true;
break;
}
}
if (currentRadioIsValid === false) {
invalidRadios[] = radiosToValidate[i];
}
}
if (invalidRadios.length > 0) {
alert('At least one radio button has not been selected');
return false;
}
return true;
}
Your comparison has a single =, not a ==. You are assigning and testing "", which is falsy so your if statement will never execute.
The operator to compare two values is ==.
Use this:
if (document.getElementsByName('v1').value== "") {
// ...
}

Read value of row using jquery

I need to create sum of the values selected, but i have small problem with the jquery bit.
My html table
<TR>
<TD>
<INPUT disabled onchange=updateDetails() value=33441 CHECKED type=checkbox name=invoiceRow dpieagent_iecontroltype="5"><INPUT value=false type=hidden name=isProfFee></TD>
<TD>Professional fees for Searches</TD>
<TD>285.00</TD></TR>
<TR>
<TD><INPUT onchange=updateDetails() value=36486 CHECKED type=checkbox name=invoiceRow dpieagent_iecontroltype="5"><INPUT value=false type=hidden name=isProfFee></TD>
<TD>Professional fees</TD>
<TD>3213.03</TD></TR>
my javascript is:
where #InvoiceItemsRows is <tbody> tag
function updateDetails() {
$("#InvoiceItemsRows input[type=checkbox][checked]").parent().last().each(
function(index, value) {
alert(value.html());
}
);
}
Javascript, maybe not as fancy as some of the other ones people have posted but it makes sense.
$(document).ready(function() {
$('[name=invoiceRow]').click(function() {
updateDetails();
});
function updateDetails() {
var total = 0;
var currentnum = 0;
$("input:checked").each(
function(index, value) {
currentnum = $(this).val();
currentnum = Number(currentnum);
total = total + currentnum;
});
alert(total);
}
});
HTML
<TR>
<TD>
<INPUT disabled value="33441" CHECKED type="checkbox" name="invoiceRow" dpieagent_iecontroltype="5"><INPUT value=false type=hidden name=isProfFee></TD>
<TD>Professional fees for Searches</TD>
<TD>285.00</TD></TR>
<TR>
<TD><INPUT value="36486" CHECKED type="checkbox" name="invoiceRow" dpieagent_iecontroltype="5"><INPUT value=false type=hidden name=isProfFee></TD>
<TD>Professional fees</TD>
<TD>3213.03</TD></TR>
I fixed some of the missing quotes you may want to finish fixing them though.
Try this (you have to close <Input> tags):
function updateDetails() {
var sum = 0;
$("#InvoiceItemsRows input[type=checkbox]:checked").each(
function() {
sum += parseFloat($(this).closest('tr').children('td:eq(2)').text());
}
);
return sum;
}
alert(updateDetails());
You'll have to change:
$("#InvoiceItemsRows input[type=checkbox][checked]")
To:
$("#InvoiceItemsRows input:checked")
That new rule will return all 'checked' elements. Have a look at the documentation of the :checked selector.
Try this:
var total = 0;
$('#InvoiceItemsRows input:checked').each(function() {
total += $(this).val();
});
I suspect you want to total what's in the <td> though?
you have invalid html your your values need quotes
<tr>
<td>
<input disabled="disabled" onchange="updateDetails()" value="33441" checked="checked" type="checkbox" name="invoiceRow" dpieagent_iecontroltype="5"> <input type="hidden" name="isProfFee">
</td>
<td>
Professional fees for Searches
</td>
<td>
285.00
</td>
</tr>
<tr>
<td>
<input onchange="updateDetails()" value="36486" checked="checked" type="checkbox" name="invoiceRow" dpieagent_iecontroltype="5"> <input type="hidden" name="isProfFee">
</td>
<td>
Professional fees
</td>
<td>
3213.03
</td>
</tr>
and then
$("#InvoiceItemsRows input:checked")

Categories