HTML input in table not responding to onkeyup - javascript

Here is the code initializing my Table:
<table cellspacing="0">
<caption id="title4">
Sprinkles (5 - 6 oz.)
</caption>
<thead>
<tr>
<th> </th>
<td >Price</td>
<td >Quantity</td>
</tr>
</thead>
<tbody>
<tr class="statement4">
<th><label>Lemon</label></th>
<td title="Yes" >
<label>$6.50</label>
</td>
<td title="No" >
<input id="s1" name="s1" class="field text small" type="text" value="0"/>
</td>
<tr class="statement4">
<th><label>Sweet Apple</label></th>
<td title="Yes" >
<label>$6.50</label>
</td>
<td title="No" >
<input id="s2" name="s2" class="field text small" type="text" value="0"/>
</td>
<tr class="statement4">
<th><label>Sweet Caramel</label></th>
<td title="Yes" >
<label>$6.50</label>
</td>
<td title="No" >
<input id="s3" name="s3" class="field text small" type="text" value="0"/>
</td>
<tr class="statement4">
<th><label>Sweet Cinnamon</label></th>
<td title="Yes" >
<label>$6.50</label>
</td>
<td title="No" >
<input id="s4" name="s4" class="field text small" type="text" value="0"/>
</td>
<tr class="statement4">
<th><label>Sweet Mocha</label></th>
<td title="Yes" >
<label>$6.50</label>
</td>
<td title="No" >
<input id="s5" name="s5" class="field text small" type="text" value="0"/>
</td>
</tr>
</tbody>
</table>
And here is my javascript:
<script type="text/javascript">
var total = 0.0;
var all=new Array();
for(var i = 0; i < 49; i++)
all[i] = 0;
//....I OMMITTED CODE HERE FOR THE REST OF THE onkeyup FUNCTIONS
document.getElementById("s1").onkeyup = function() {
if(this.value != "") {
all[44] = (parseInt(this.value,10) * 6.50);
}
else {
all[44] = 0;
}
updateIt();
};
document.getElementById("s2").onkeyup = function() {
if(this.value != "") {
all[45] = (parseInt(this.value,10) * 6.50);
}
else {
all[45] = 0;
}
updateIt();
};
document.getElementById("s3").onkeyup = function() {
if(this.value != "") {
all[46] = (parseInt(this.value,10) * 6.50);
}
else {
all[46] = 0;
}
updateIt();
};
document.getElementById("s4").onkeyup = function() {
if(this.value != "") {
all[47] = (parseInt(this.value,10) * 6.50);
}
else {
all[47] = 0;
}
updateIt();
};
document.getElementById("s5").onkeyup = function() {
document.getElementById("mySpan").innerHTML = "WOAH";
if(this.value != "") {
all[48] = (parseInt(this.value,10) * 6.50);
}
else {
all[48] = 0;
}
updateIt();
};
function updateIt() {
var theTotal = 0;
for(var j = 0; j < 49; j++)
theTotal += all[j];
theTotal = all[48];
document.getElementById("mySpan").innerHTML = "$" + theTotal.toFixed(2);
}
</script>
Note that I have more tables and other onKeyUp functions declared, but for some reason all the tables after this table (I have about 6 tables, and the first 3 work properly), do not respond to their respective onkeyup events.
Here is code for the last table that worked (this code is right above the code creating the table I posted above):
<table cellspacing="0">
<caption id="title4">
Rubs (1.2 - 2.3oz.)
</caption>
<thead>
<tr>
<th> </th>
<td >Price</td>
<td >Quantity</td>
</tr>
</thead>
<tbody>
<tr class="statement4">
<th><label>Buffalo</label></th>
<td title="Yes" >
<label>$4.25</label>
</td>
<td title="No" >
<input id="rubs1" name="rubs1" class="field text small" type="text" value="0"/>
</td>
<tr class="statement4">
<th><label>Chipotle</label></th>
<td title="Yes" >
<label>$4.25</label>
</td>
<td title="No" >
<input id="rubs2" name="rubs2" class="field text small" type="text" value="0"/>
</td>
<tr class="statement4">
<th><label>Citrus</label></th>
<td title="Yes" >
<label>$4.25</label>
</td>
<td title="No" >
<input id="rubs3" name="rubs3" class="field text small" type="text" value="0"/>
</td>
<tr class="statement4">
<th><label>Creole</label></th>
<td title="Yes" >
<label>$4.25</label>
</td>
<td title="No" >
<input id="rubs4" name="rubs4" class="field text small" type="text" value="0"/>
</td>
<tr class="statement4">
<th><label>Crushed Peppercorn & Garlic</label></th>
<td title="Yes" >
<label>$4.25</label>
</td>
<td title="No" >
<input id="rubs5" name="rubs5" class="field text small" type="text" value="0"/>
</td>
<tr class="statement4">
<th><label>Greek</label></th>
<td title="Yes" >
<label>$4.25</label>
</td>
<td title="No" >
<input id="rubs6" name="rubs6" class="field text small" type="text" value="0"/>
</td>
<tr class="statement4">
<th><label>Jamaican Jerk</label></th>
<td title="Yes" >
<label>$4.25</label>
</td>
<td title="No" >
<input id="rubs7" name="rubs7" class="field text small" type="text" value="0"/>
</td>
<tr class="statement4">
<th><label>Lemon Pepper</label></th>
<td title="Yes" >
<label>$4.25</label>
</td>
<td title="No" >
<input id="rubs8" name="rubs8" class="field text small" type="text" value="0"/>
</td>
<tr class="statement4">
<th><label>Moroccan/label></th>
<td title="Yes" >
<label>$4.25</label>
</td>
<td title="No" >
<input id="rubs9" name="rubs9" class="field text small" type="text" value="0"/>
</td>
<tr class="statement4">
<th><label>Smoky Barbecue</label></th>
<td title="Yes" >
<label>$4.25</label>
</td>
<td title="No" >
<input id="rubs10" name="rubs10" class="field text small" type="text" value="0"/>
</td>
<tr class="statement4">
<th><label>Thai Red Curry</label></th>
<td title="Yes" >
<label>$4.25</label>
</td>
<td title="No" >
<input id="rubs11" name="rubs11" class="field text small" type="text" value="0"/>
</td>
</tr>
</tbody>
</table>

var theTotal = 0;
for(var j = 0; j < 49; j++)
theTotal += all[j];
theTotal = all[48];
Why are you doing this? First you calculate the sum of all prices, then you assign only the last value to theTotal. This seems wrong to me.

You are missing an element by id "mySpan" though you are looking for it in your JS(document.getElementById("mySpan").innerHTML ), hence it is erroring out.
Add a HTML element with that ID and it should work.
Check jsfiddle: http://jsfiddle.net/Chandu/yVaMx/5/

Related

Filter Table per columb

I have code here which filtering table doesn't work, then I want the status filter with checkbox, what I have to do?, please help me!
var $rows = $('tbody > tr'),
$filters = $('#filter_table input');
$filters.on("keyup", function () {
var $i = $filters.filter(function () {
return $.trim(this.value).length > 0;
}),
len = $i.length;
if (len === 0) return $rows.show();
var cls = '.' + $i.map(function () {
return this.className
}).get().join(',.');
$rows.hide().filter(function () {
return $('td', this).filter(cls).filter(function () {
var content = this.textContent,
inputVal = $i.filter('.' + this.className).val();
return content.toLowerCase().indexOf(inputVal.toLowerCase()) > -1;
}).length === len;
}).show();
});
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<div class="panel panel-default" id="filter_table">
Input here to Search <br>
<input type='text' class='Program' id='Program' style="width: 100px;" placeholder="Program" />
<input type='text' class='Year' id='Year' style="width: 100px;" placeholder="Year" />
<input type='text' class='Province' id='Province' style="width: 100px;" placeholder="Province" />
<input type='text' class='LGU' id='LGU' style="width: 100px;" placeholder="LGU" />
<input type='text' class='Barangay' id='Barangay' style="width: 100px;" placeholder="Barangay" />
<input type='text' class='Project' id='Project' style="width: 100px;" placeholder="Project" />
<input type='text' class='Allocation' id='Allocation' style="width: 100px;" placeholder="Allocation" />
<input type='text' class='Status' id='Status' style="width: 100px;" placeholder="Status" />
</div>
<table border='1' class="table table-hover" id='products'>
<thead>
<tr>
<th width="10px">Program
</th>
<th width="10px">Year
</th>
<th width="20px">Province
</th>
<th width="20px">Municipality/LGU
</th>
<th width="20px">Barangay
</th>
<th width="30px">Project
</th>
<th width="20px">Allocation
</th>
<th width="20px">Status
</th>
<th width="5px">PA%
</th>
</tr>
</thead>
<tbody>
<tr>
<td width="10px">Program1
</td>
<td width="10px">2012
</td>
<td width="20px">Province1
</td>
<td width="20px">Municipality/LGU1
</td>
<td width="20px">Barangay1
</td>
<td width="30px">Project1
</td>
<td width="20px">200000
</td>
<td width="20px">completed
</td>
<td width="5px">100%
</td>
</tr>
<tr>
<td width="10px">Program1
</td>
<td width="10px">2013
</td>
<td width="20px">Province2
</td>
<td width="20px">Municipality/LGU2
</td>
<td width="20px">Barangay2
</td>
<td width="30px">Project2
</td>
<td width="20px">500000
</td>
<td width="20px">ongoing
</td>
<td width="5px">50%
</td>
</tr>
<tr>
<td width="10px">Program3
</td>
<td width="10px">2014
</td>
<td width="20px">Province3
</td>
<td width="20px">Municipality/LGU3
</td>
<td width="20px">Barangay3
</td>
<td width="30px">Project3
</td>
<td width="20px">6000000
</td>
<td width="20px">suspended
</td>
<td width="5px">0%
</td>
</tr>
<tr>
<td width="10px">Program4
</td>
<td width="10px">2016
</td>
<td width="20px">Province4
</td>
<td width="20px">Municipality/LGU4
</td>
<td width="20px">Barangay4
</td>
<td width="30px">Project4
</td>
<td width="20px">1000000
</td>
<td width="20px">cancelled
</td>
<td width="5px">0%
</td>
</tr>
</tbody>
</table>
Thank you in advance!
What you have done in your javaScript / Jquery side is correct. You missed to add the relevant class names to your HTML. I added classes for year (and I made a change to have 2 records for 2012) and allocation and it seems working.
Try searching with year = 2012 and allocation = 200000
var $rows = $('tbody > tr'),
$filters = $('#filter_table input');
$filters.on("keyup", function () {
var $i = $filters.filter(function () {
return $.trim(this.value).length > 0;
}),
len = $i.length;
if (len === 0) return $rows.show();
var cls = '.' + $i.map(function () {
return this.className
}).get().join(',.');
$rows.hide().filter(function () {
return $('td', this).filter(cls).filter(function () {
var content = this.textContent,
inputVal = $i.filter('.' + this.className).val();
return content.toLowerCase().indexOf(inputVal.toLowerCase()) > -1;
}).length === len;
}).show();
});
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<div class="panel panel-default" id="filter_table">
Input here to Search <br>
<input type='text' class='Program' id='Program' style="width: 100px;" placeholder="Program" />
<input type='text' class='Year' id='Year' style="width: 100px;" placeholder="Year" />
<input type='text' class='Province' id='Province' style="width: 100px;" placeholder="Province" />
<input type='text' class='LGU' id='LGU' style="width: 100px;" placeholder="LGU" />
<input type='text' class='Barangay' id='Barangay' style="width: 100px;" placeholder="Barangay" />
<input type='text' class='Project' id='Project' style="width: 100px;" placeholder="Project" />
<input type='text' class='Allocation' id='Allocation' style="width: 100px;" placeholder="Allocation" />
<input type='text' class='Status' id='Status' style="width: 100px;" placeholder="Status" />
</div>
<table border='1' class="table table-hover" id='products'>
<thead>
<tr>
<th width="10px">Program
</th>
<th width="10px">Year
</th>
<th width="20px">Province
</th>
<th width="20px">Municipality/LGU
</th>
<th width="20px">Barangay
</th>
<th width="30px">Project
</th>
<th width="20px">Allocation
</th>
<th width="20px">Status
</th>
<th width="5px">PA%
</th>
</tr>
</thead>
<tbody>
<tr>
<td width="10px">Program1
</td>
<td width="10px" class='Year'>2012
</td>
<td width="20px">Province1
</td>
<td width="20px">Municipality/LGU1
</td>
<td width="20px">Barangay1
</td>
<td width="30px">Project1
</td>
<td width="20px" class='Allocation'>200000
</td>
<td width="20px">completed
</td>
<td width="5px">100%
</td>
</tr>
<tr>
<td width="10px">Program1
</td>
<td width="10px" class='Year'>2012
</td>
<td width="20px">Province2
</td>
<td width="20px">Municipality/LGU2
</td>
<td width="20px">Barangay2
</td>
<td width="30px">Project2
</td>
<td width="20px" class='Allocation'>500000
</td>
<td width="20px">ongoing
</td>
<td width="5px">50%
</td>
</tr>
<tr>
<td width="10px">Program3
</td>
<td width="10px" class='Year'>2014
</td>
<td width="20px">Province3
</td>
<td width="20px">Municipality/LGU3
</td>
<td width="20px">Barangay3
</td>
<td width="30px">Project3
</td>
<td width="20px" class='Allocation'>6000000
</td>
<td width="20px">suspended
</td>
<td width="5px">0%
</td>
</tr>
<tr>
<td width="10px">Program4
</td>
<td width="10px" class='Year'>2016
</td>
<td width="20px">Province4
</td>
<td width="20px">Municipality/LGU4
</td>
<td width="20px">Barangay4
</td>
<td width="30px">Project4
</td>
<td width="20px" class='Allocation'>1000000
</td>
<td width="20px">cancelled
</td>
<td width="5px">0%
</td>
</tr>
</tbody>
</table>
I have changed code and working for status as well
fiddle: https://codepen.io/creativedev/pen/yEOPbz
$(document).ready(function(){
var $rows = $('tbody > tr'),
$filters = $('#filter_table input');
$filters.on("keyup", function () {
var $i = $filters.filter(function () {
return $.trim(this.value).length > 0;
});
var len = $i.length;
if (len === 0)
return $rows.show();
var cls = '.' + $i.map(function () {
return this.className;
}).get().join(',.');
if(cls.indexOf(",") > -1){
var array = cls.split(",");
$.each(array,function(i){
$rows.hide().filter(function () {
return $('td', this).filter(function () {//console.log(this);
var content = this.textContent,
inputVal = $i.filter(array[i]).val();
return content.toLowerCase().indexOf(inputVal.toLowerCase()) > -1;
}).length == len;
}).show();
});
}else{
$rows.hide().filter(function () {
return $('td', this).filter(function () {
var content = this.textContent,
inputVal = $i.filter(cls).val();
return content.toLowerCase().indexOf(inputVal.toLowerCase()) > -1;
}).length === len;
}).show();
}
});
});

How to disable all checkboxes when page loads in jquery?

I'm working on this table that has checkboxes for each row. Basically, I want all of the email input fields to be disabled once page loads. If the users clicks on the checkbox that belongs to a row then the email input field for that row should be enabled so the user can type in an email. Finally, if the user clicks on the Select all checkbox all of the input fields should be enabled/disabled. For some reason I can only disabled the first, second and last input field once page loads. My Select All checkbox is not working properly either :(. Can anyone tell me what I'm doing wrong please? Thanks in advance!
var users = $("tr")
.filter(function () {
return $(this).find('.inputEmail').val() !== "" && $(this).find(".input_checkbox").is(':checked');
})
.map(function () {
var $row = $(this);
return {
firstName: $row.find('.fullName').text(),
number: $row.find('.usersPhoneNumber').text(),
email: $row.find('.inputEmail').val()
}
})
.get();
console.log('Array containing all users with an email:');
console.log(users);
Here's my code - LIVE DEMO:
$(document).ready(function() {
$("#checkAll").change(function() {
$(".input_checkbox").prop('checked', $(this).prop("checked")).each(function() {
enable_disable_input(this);
var nameValue = $(this).attr("name");
var inputFieldNameValue = $.trim(nameValue);
var inputFieldString = "customer-name-inputField";
var inputFieldId = inputFieldNameValue + inputFieldString;
if ($(this).is(":checked")) {
enable_disable_input(this);
$("#" + inputFieldId).prop('placeholder', "Enter email address");
} else {
$("#" + inputFieldId).prop('placeholder', "");
enable_disable_input(this);
}
});
});
function enable_disable_input(checkbox) {
var input_id = checkbox.id.replace('-checkbox', '-inputField');
$("#" + input_id).prop('disabled', !checkbox.checked);
}
$(".input_checkbox").change(function() {
var nameValue = $(this).attr("name");
var inputFieldNameValue = $.trim(nameValue);
var inputFieldString = "customer-name-inputField";
var inputFieldId = inputFieldNameValue + inputFieldString;
if ($(this).is(":checked")) {
enable_disable_input(this);
$("#" + inputFieldId).prop('placeholder', "Enter email address");
} else {
$("#" + inputFieldId).prop('placeholder', "");
enable_disable_input(this);
}
});
$(".input_checkbox").each(function() {
enable_disable_input(this);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<div style="width:1140px;">
<br/>
<table>
<div>
<tr>
<td align="center" valign="bottom">Select All
<br/>
<input type="checkbox" id="checkAll" value="" />
</td>
<td width="5"></td>
<td width="200" valign="bottom">Name</td>
<td align="center" class="table-col-phone" style="padding-left:20px;">Phone # / Extension</td>
<td width="50"></td>
<td valign="bottom" style="padding-left: 90px;">Email</td>
</tr>
<tr>
<td style="font-weight: bold;">Group1</td>
</tr>
<tr>
<td></td>
<td align="center">
<input class="input_checkbox" type="checkbox" id="0customer-name-checkbox" name="0 " value="">
</td>
<td class="fullName">Ben Morris</td>
<td align="left" class="usersPhoneNumber">3033422109</td>
<td width="50"></td>
<td>
<input type="email" class="inputEmail" name="0" id="0customer-name-inputField" placeholder="" value="" />
<br/>
<br/>
</td>
</tr>
<tr>
<td align="center"></td>
<td align="center">
<input class="input_checkbox" type="checkbox" id="1customer-name-checkbox" name="1 " value="">
</td>
<td class="fullName">Mike Jeff</td>
<td align="left" class="usersPhoneNumber">3037777777</td>
<td width="50"></td>
<td>
<input type="email" class="inputEmail" name="1" id="1customer-name-inputField" placeholder="" value="" />
<br/>
<br/>
</td>
</tr>
<tr>
<td style="font-weight: bold;">Group2</td>
</tr>
<tr>
<td></td>
<td align="center">
<input class="input_checkbox" type="checkbox" id="0customer-name-checkbox" name="0 " value="">
</td>
<td class="fullName">Ana McLwius</td>
<td align="left" class="usersPhoneNumber">3039899231</td>
<td width="50"></td>
<td>
<input type="email" class="inputEmail" name="0" id="0customer-name-inputField" placeholder="" value="" />
<br/>
<br/>
</td>
</tr>
<tr>
<td align="center"></td>
<td align="center">
<input class="input_checkbox" type="checkbox" id="1customer-name-checkbox" name="1 " value="">
</td>
<td class="fullName">Zumia Brown</td>
<td align="left" class="usersPhoneNumber">3033213453</td>
<td width="50"></td>
<td>
<input type="email" class="inputEmail" name="1" id="1customer-name-inputField" placeholder="" value="" />
<br/>
<br/>
</td>
</tr>
<tr>
<td style="font-weight: bold;">Group3</td>
</tr>
<tr>
<td></td>
<td align="center">
<input class="input_checkbox" type="checkbox" id="0customer-name-checkbox" name="0 " value="">
</td>
<td class="fullName">Bryan Smith</td>
<td align="left" class="usersPhoneNumber">3033222098</td>
<td width="50"></td>
<td>
<input type="email" class="inputEmail" name="0" id="0customer-name-inputField" placeholder="" value="" />
<br/>
<br/>
</td>
</tr>
<tr>
<td align="center"></td>
<td align="center">
<input class="input_checkbox" type="checkbox" id="1customer-name-checkbox" name="1 " value="">
</td>
<td class="fullName">Junior White</td>
<td align="left" class="usersPhoneNumber">3030098342</td>
<td width="50"></td>
<td>
<input type="email" class="inputEmail" name="1" id="1customer-name-inputField" placeholder="" value="" />
<br/>
<br/>
</td>
</tr>
<tr>
<td align="center"></td>
<td align="center">
<input class="input_checkbox" type="checkbox" id="2customer-name-checkbox" name="2 " value="">
</td>
<td class="fullName">Peter McDonald</td>
<td align="left" class="usersPhoneNumber">3037777777</td>
<td width="50"></td>
<td>
<input type="email" class="inputEmail" name="2" id="2customer-name-inputField" placeholder="" value="" />
<br/>
<br/>
</td>
</tr>
</div>
</table>
<button id="submitButton" type="button" class="sign-in-button" style="text-align: center;margin-left: 428px;" value="Submit" />Submit</button>
</div>
You should search email input based on the current element. You are having duplicate ids.
try this:
$(this).closest('tr').find('input[type;"text"]').attr("disabled", !this.checkbox);
Updated Fiddle
Note I have taken leisure to update your code. Hope it helps!
Getting Data
You can try something like this:
Note I have updated Group label rows and have added class in it.
Updated Fiddle
$("#submitButton").on("click", function() {
var result = {};
var group_id = "";
$("table tr").each(function(index, row) {
var $row = $(row)
group_id = $row.hasClass("section-label") ? $row.find("td:first").text() : group_id;
if (group_id && $row.find(".input_checkbox").is(':checked') && $row.find('.inputEmail').val().trim() !== "") {
result[group_id] = result[group_id] || [];
result[group_id].push({
firstName: $row.find('.fullName').text(),
number: $row.find('.usersPhoneNumber').text(),
email: $row.find('.inputEmail').val()
});
}
});
console.log(result)
})
Obviously because of the duplicated ids.
try this:
function enable_disable_input(checkbox) {
$(checkbox).parents('tr').find('input[type="email"]').prop('disabled', !checkbox.checked);
}
Your code seems a little messy, something like this would work and it's more readable
$(document).ready(function () {
$("#checkAll").change(function () {
$(".input_checkbox").prop('checked', $(this).prop("checked")).each(function () {
var input = $(this).parent().parent().find("input[type='email']");
if ($(this).is(":checked")) {
$(input).prop('disabled', false);
$(input).prop('placeholder', "Enter email address");
}
else {
$(input).prop('placeholder', "");
$(input).prop('disabled', true);
}
});
});
$(".input_checkbox").change(function () {
var input = $(this).parent().parent().find("input[type='email']");
if ($(this).is(":checked")) {
$(input).prop('disabled', false);
$(input).prop('placeholder', "Enter email address");
}
else {
$(input).prop('placeholder', "");
$(input).prop('disabled', true);
}
});
$('.inputEmail').each(function(){
$(this).prop('disabled', true);
})
});
full working example
Also, you should remove the duplicated ID's.

Multiple instances of same calculator in Javascript

I am new to Javascript and trying to create an on-line score tracker for a card game I play called Hand and Foot. The rules are this, 3 teams play 4 games, the team with the most points at the end wins. I have created a calculator for 1 person for 1 game, but when I duplicate it for the 11 more instances I need, the calculations stop working which I believe has to do with the getElementById not registering with the multiple instances in the html. I would be grateful suggestions on a more elegant way to create instances of this calculator on the same page without having to change the IDs of each field for each play and each game. check out my code Fiddle
<div class="P1G1">
<h1>Game 1</h1>
<form id="calcP1G1">
<h2>Neccessary Piles</h2>
<table>
<td>Clean</td>
<td align="center">
<input id="necCleanP1G1" type="checkbox" class="addon" value="500">
</td>
<td>Dirty</td>
<td align="center">
<input id="necDirtyP1G1" type="checkbox" class="addon" value="300">
</td>
<td>Sevens</td>
<td align="center">
<input id="necSevenP1G1" type="checkbox" class="addon" value="5000">
</td>
<td>Fives</td>
<td align="center">
<input id="necFiveP1G1" type="checkbox" class="addon" value="3000">
</td>
<td>Wilds</td>
<td align="center">
<input id="necWildP1G1" type="checkbox" class="addon" value="2500">
</td>
<td id="necTotalP1G1" style="display:none"></td>
</table>
<hr>
<table>
<tr>
<th class="pile-header">Clean Piles</th>
<th></th>
</tr>
<tr>
<td class="input-number">
<input id="cleanP1G1" type="text" value="0" oninput="calculate()" class="form-control" />
</td>
<td class="result-number">
<input id="resultCleanP1G1" disabled="disabled" class="form-control" />
</td>
</tr>
<tr>
<th class="pile-header">Dirty Piles</th>
<th></th>
</tr>
<tr>
<td class="input-number">
<input id="dirtyP1G1" type="text" oninput="calculate()" value="0" class="form-control" />
</td>
<td class="result-number">
<input id="resultDirtyP1G1" disabled="disabled" class="form-control" />
</td>
</tr>
<tr>
<th class="pile-header">Red 3s</th>
<th></th>
</tr>
<tr>
<td class="input-number">
<input id="redThreeP1G1" oninput="calculate()" value="0" class="form-control" />
</td>
<td class="result-number">
<input id="resultRedThreeP1G1" disabled="disabled" class="form-control" />
</td>
</tr>
<tr>
<th class="pile-header">Card Count</th>
<th></th>
</tr>
<tr>
<td class="input-number">
<input id="cardsP1G1" oninput="calculate()" value="0" class="form-control" />
</td>
<td class="result-number">
<input id="resultCardP1G1" disabled="disabled" class="form-control" />
</td>
</tr>
<tr>
<td class="pile-header">Total</td>
<td class="result-number">
<input id="resultTotalP1G1" disabled="disabled" class="form-control" />
</td>
</tr>
</table>
</form>
</div>
Javascript
function updateTotal() {
var add = 0;
var form = document.getElementById("calcP1G1");
var checkboxes = form.getElementsByClassName('addon');
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
add += parseInt(checkboxes[i].value, 10);
}
}
var amount = document.getElementById("necTotalP1G1").innerHTML = add;
}
document.getElementById("calcP1G1").addEventListener('change', updateTotal);
// Run it once at startup
updateTotal();
function calculate() {
var topCards = document.getElementById("necTotalP1G1").innerHTML;
var cleanBox = document.getElementById("cleanP1G1").value;
var totalClean = document.getElementById("resultCleanP1G1");
var resultClean = cleanBox * 500;
totalClean.value = resultClean;
//---------------------//
var dirtyBox = document.getElementById("dirtyP1G1").value;
var totalDirty = document.getElementById("resultDirtyP1G1");
var resultDirty = dirtyBox * 300;
totalDirty.value = resultDirty;
//---------------------//
var redThreeBox = document.getElementById("redThreeP1G1").value;
var totalRedThree = document.getElementById("resultRedThreeP1G1");
var resultRedThree = redThreeBox * 100;
totalRedThree.value = resultRedThree;
//---------------------//
var cardBox = document.getElementById("cardsP1G1").value;
var totalCard = cardBox;
document.getElementById("resultCardP1G1").value = totalCard;
//---------------------//
var total = parseInt(resultDirty) + parseInt(resultClean) + parseInt(resultRedThree) + parseInt(totalCard) + parseInt(topCards);
document.getElementById("resultTotalP1G1").value = total;
}
document.getElementById("calcP1G1").addEventListener('change', calculate);
// Run it once at startup
calculate();

Javascript: Add multiple fields together and insert into Totals column on Form

I am new to javascript and am making a basic HTML timesheet form. I am simply trying to add the various hour types (Regular, overtime, sick, etc.) together and put that calculated value into a "Total hours" text box. Here is my function that I attempted (I am only using the 1 text box for now but would like advice on how to incorporate the others):
<script>
function findTotal(hours, tot) {
var hours = document.getElementsbyID('hours1').value;
var tot = 0;
for (var i = 0; i < hours.length; i++) {
if (parseInt(hours[i].value))
tot += parseInt(hours[i].value);
}
document.getElementById('total').value = tot;
}
</script>
Here is the corresponding HTML form section:
<b>HOURS</b>
<table width="25%" border="1" cellpadding="0" cellspacing="0" style="background-color: #ffffff;">
<tr valign="Top">
<td style="border-width : 0px;">
<br /><b>Regular</b>
</td>
<td style="border-width : 0px;">
<br />
<input type="text" onblur="findTotal(hours)" id="hours1" size="5">
</td>
</tr>
<tr valign="top">
<td style="border-width : 0px;">
<br /><b>Overtime</b>
</td>
<td style="border-width : 0px;">
<br />
<input type="text" onblur="findTotal()" id="hours2" size="5">
</td>
</tr>
<tr valign="top">
<td style="border-width : 0px;">
<br /><b>Sick</b>
</td>
<td style="border-width : 0px;">
<br />
<input type="text" onblur="findTotal()" id="hours3" size="5">
</td>
</tr>
<tr valign="top">
<td style="border-width : 0px;">
<br /><b>Holiday</b>
</td>
<td style="border-width : 0px;">
<br />
<input type="text" onblur="findTotal()" id="hours4" size="5">
</td>
</tr>
<tr valign="top">
<td style="border-width : 0px;">
<br /><b>Vacation</b>
</td>
<td style="border-width : 0px;">
<br />
<input type="text" onblur="findTotal()" id="hours5" size="5">
</td>
</tr>
<tr valign="top">
<td style="border-width : 0px;">
<br /><b>Leave</b>
</td>
<td style="border-width : 0px;">
<br />
<input type="text" onblur="findTotal()" id="hours6" size="5">
</td>
</tr>
<tr valign="top">
<td style="border-width : 0px;">
<br /><b>Jury Duty</b>
</td>
<td style="border-width : 0px;">
<br />
<input type="text" onblur="findTotal()" id="hours7" size="5">
</td>
</tr>
<tr valign="top">
<td style="border-width : 0px;">
<br /><b>TOTAL HOURS</b>
</td>
<td style="border-width : 0px;">
<br />
<input type="text" onblur="findTotal()" size="5" id="total">
</td>
</tr>
</table>
Thank you in advance for your help!
-Matt
If you do the same things many times, think about how you could do it generically with CSS (selector) or JavaScript (loop).
Cleaned up HTML:
<b>HOURS</b>
<table id="myTable" width="25%">
<tr valign="top">
<td>Regular</td>
<td>
<input type="text" size="5" />
</td>
</tr>
<tr valign="top">
<td>Overtime</td>
<td>
<input type="text" size="5" />
</td>
</tr>
<tr valign="top">
<td>Sick</td>
<td>
<input type="text" size="5" />
</td>
</tr>
<tr valign="top">
<td>Holiday</td>
<td>
<input type="text" id="hours4" size="5" />
</td>
</tr>
<tr valign="top">
<td>Vacation
</td>
<td>
<input type="text" size="5" />
</td>
</tr>
<tr valign="top">
<td>Leave</td>
<td>
<input type="text" size="5" />
</td>
</tr>
<tr valign="top">
<td>Jury Duty</td>
<td>
<input type="text" size="5" />
</td>
</tr>
<tr valign="top">
<td>TOTAL HOURS</td>
<td>
<input type="text" size="5" id="total" />
</td>
</tr>
</table>
It is good pratice to separate JavaScript and HTML.
If you work with HTML and JavaScript, it's good to understand how you could access, e.g here the table, without class (getElementsByClassName) and without id (getElementById).
Go through the table rows in the table. Therefore there are rows and cells:
var table = document.getElementById("myTable");
var rows = table.rows;
var rowsLength = rows.length // the number of all rows in the table
Example first row first cell:
var firstRowFirstCell = rows[0].cells[0];
Here, we go through the rows without the last row (total) rowsLength - 1. The input is in the second cell. Therefore we need document.getElementsByTagName
var input = rows[i].cells[1].getElementsByTagName("input");
to add addEventListener:
input[0].addEventListener("blur", function() { ... });
for every input except total (the last one). Assign
function totalHours(containerID) {
var table = document.getElementById(containerID);
var rows = table.rows;
var rowsLength = rows.length;
var total = 0;
for(var i = 0; i < (rowsLength - 1); i += 1) { // not the TOTAL input!
var input = rows[i].cells[1].getElementsByTagName("input");
if(input[0].value !== "") { // no empty inputs
total += parseInt(input[0].value);
}
}
return total;
}
to them.
Full example

How to get the dynamically cloned table textbox value?

All,
I have table which I am cloning on clicking on button and after cloning table I need to do few calculation in the cloned table as well as in parent table. My problem is that I am not able to do calculation on each appended(clone) table. I mean I wrote a on blur function to do calculation with textbox value but when I am cloning table since class name is same for all textbox, in parent and cloned table my result showing in all textbox instead of corresponding part of the table. Here is my table and my jquery code which I am following.
<html>
<body>
<table>
<tbody>
<tr><td>
<table width="95%" border="0" cellspacing="5" cellpadding="5" style="margin-left:10px;" id="product">
<thead><tr>
<td class="mandatory"> * Product Name </td>
<td class="label"> Qty.in Stock</td>
<td class="mandatory">* Qty </td>
<td class="mandatory">* Unit Price</td>
<td class="mandatory">* List Price</td>
<td class="mandatory">* Total</td>
</tr>
</thead>
<tbody class="product_details" id="tbody_product">
<tr class="tr_product_details">
<td>
<input type="text" name="txtproductName[]" id="product-name" />
<a href="">
<img width="17" height="16" src="images/Products_small.gif"> </a>
<input type="hidden" name="productid[]" id="productid" />
</td>
<td>
<input type="text" name="txtqtyStock[]" id="productstock" />
</td>
<td>
<input type="text" name="txtQty" id="product-quatity" class="product-qty" value="3" />
</td>
<td>
<input type="text" name="txtUnitPrice[]" id="product-price" />
</td>
<td>
<input type="text" name="txtListPrice[]" id="product-list-price" class="product-list-price"
/>
</td>
<td><div style="margin-left:120px;">
<input type="text" name="txtTotal[]" size="10" class="total-price" />
</div>
</td>
</tr>
<tr>
<td colspan="5"> <img width="17" height="16" src="images/spacer.gif">Product Description </td>
</tr>
<tr>
<td colspan="5"><textarea style="width:65%" maxlength="250" rows="3" cols="30" name="txtProductDescription[]" id="textarea-product-description"></textarea>
</td>
<td colspan="1" class="tbl">
<table >
<tr>
<td>Discount: </td>
<td> <input type="text" name="txtProductDiscount[]" size="10" class="product-discount" /></td>
</tr>
<tr>
<td class="label">Total After Discount: </td>
<td> <input type="text" name="txtAfterDiscount[]" size="10" class="total-after-discount" /></td>
</tr>
<tr>
<td> Tax: </td>
<td><input type="text" name="txtProductTax[]" size="10" />
</td>
</tr>
<tr>
<td class="label"> Net Total: </td>
<td><input type="text" name="txtNetTotal[]" size="10" class="net-total" /> </td>
</tr>
</table>
</td>
</tr>
</tbody>
</table>
<table align="left" style="margin-left:20px;">
<tr>
<td><input type="button" id="btnaddProduct" value="Add Product" class="button"/> </td>
</tr>
</table>
</body>
</html>
And my script which I am using :
<script type="text/javascript">
$(document).ready(function () {
var parent_qty_id = $("#product tbody:first").attr('id');
var qty_attr = parent_qty_id+" tr:first .product-qty";
$("#"+qty_attr+" .product-qty").bind("blur change",function(){
var product_qty = $(this).val(), product_list_price = $('#product tr td .product-list-price').val(),total;
total = product_qty * product_list_price;
// alert( $(this).children().children().attr("class"));
// $(this).children().children().attr("class");
var val = $(this).children();
$(val).val(total+'.00');
});
$("#btnaddProduct").click(function() {
var count = ($("tbody .product_details").length) + 1;
var tblid = $("#product tbody:first").attr('id');
var newid = tblid+"_"+count;
$('#product tbody:first').clone(true).insertAfter('#product > tbody:last').attr("id",newid);
$('table#product > tbody:last > tr:first input').val(' ');
$('table#product > tbody:last > tr:last input').val(' ');
$(":text.product-qty").last().val();
return false;
});
});
</script>
$("#"+qty_attr+" .product-qty")
Comes out empty (no element selected) because you already added .product-qty in parent_qty_id to qty_attr.
$("#"+qty_attr)
Works.
There were alot of other errors in your code which made the blur/change routine run twice etc. I've sanitized it some into this:
$(document).ready(function () {
var parent_qty_id = $("#product tbody:first").attr('id');
var qty_attr = parent_qty_id+" tr:first .product-qty";
$("#"+qty_attr).blur(function(){
var product_qty = $(this).val(), product_list_price = $('#product tr td .product-list-price').val(),total;
total = product_qty * product_list_price;
var val = $(this).children();
$(val).val(total+'.00');
});
$("#btnaddProduct").click(function(e) {
e.preventDefault();
var count = ($("tbody .product_details").length) + 1;
var tblid = $("#product tbody:first").attr('id');
var newid = tblid+"_"+count;
$('#product tbody:first').clone(true).insertAfter('#product > tbody:last').attr("id",newid);
$('table#product > tbody:last > tr:first input').val(' ');
$('table#product > tbody:last > tr:last input').val(' ');
$(":text.product-qty").last().val();
});
});
Further tweaking is probably needed.

Categories