How to get the dynamically cloned table textbox value? - javascript

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.

Related

How to sort the rows of a table dynamically based on data-sort attribute in tr tag when its value changes

I have a table and I want to sort the rows by the user,Each row contains one input, for enter a row number. Here rows are sorted by data-sort Attribute in tr and each input has a rownum attribute whose value is equal to the value of the tr data-sort attribute.There are 6 rows here. We want to take the input value of each row, and move that row there, and the values of the attributes are the same as the input.For example, if you enter 1 in the input of one of the rows, that row will be our first row.
The following code runs for the first time, but after moving one of the rows does not work anymore.When its value changes. where is my mistake?
jsfiddle
$('.m').on('change', function () {
var Des = parseInt($(this).val());
var RowNum = parseInt($(this).attr('rownum'));
$('tr[data-sort="' + RowNum + '"]').attr('data-sort', -100);
$('input[rownum="' + RowNum + '"]').attr('rownum', -100);
if (Des > RowNum) {
for (var i = RowNum + 1; i <= Des; i++) {
var newVal = i - 1;
$('tr[data-sort="' + i + '"]').attr('data-sort', newVal);
$('input[rownum="' + i + '"]').attr('rownum', newVal);
}
}
if (Des < RowNum) {
for (var i = Des + 1; i <= (RowNum - 1); i++) {
var newVal = i + 1;
$('tr[data-sort="' + i + '"]').attr('data-sort', newVal);
$('input[rownum="' + i + '"]').attr('rownum', newVal);
}
}
$('tr[data-sort="-100"]').attr('data-sort', Des);
$('input[rownum="-100"]').attr('rownum', Des);
var divList = $("tr");
divList.sort(function (a, b) {
return (parseInt($(a).data("sort")) - parseInt($(b).data("sort")))
});
$("tbody").html(divList);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<h4>
inter value between 1-6
</h4>
<table class="table table-hover">
<tbody>
<tr id="1" data-sort="1">
<td>One</td>
<td>
<input rownum="1" class="m" />
</td>
</tr>
<tr id="2" data-sort="2">
<td>Two</td>
<td>
<input rownum="2" class="m" />
</td>
</tr>
<tr id="3" data-sort="3">
<td>Three</td>
<td>
<input rownum="3" class="m" />
</td>
</tr>
<tr id="4" data-sort="4">
<td>Four</td>
<td>
<input rownum="4" class="m" />
</td>
</tr>
<tr id="5" data-sort="5">
<td>Five</td>
<td>
<input rownum="5" class="m" />
</td>
</tr>
<tr id="6" data-sort="6">
<td>six</td>
<td>
<input rownum="6" class="m" />
</td>
</tr>
</tbody>
</table>
</div>
as you rebuild and replace html piece of code on which you have your listener, you have to rebind event listener to the new created elements with class "m". Something as below (not elegant,only here to show a working example - and you don't need all your test. You just need to assign input value to data-sort attribut and then reorder with sort function)
$('.m').on('change', function (evt) {
changeOrder(evt);
})
function changeOrder(evt){
$this=$(evt.currentTarget);
var Des = parseInt($this.val());
var RowNum = parseInt($this.attr('rownum'));
$this.parent().parent().data("sort",Des)
var divList = $("tbody").find("tr").sort(function (a, b) {
return (parseInt($(a).data("sort")) - parseInt($(b).data("sort")))
});
$("tbody").html(divList);
$('.m').on('change', function (evt) {
changeOrder(evt);
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="container">
<h4>
inter value between 1-6
</h4>
<table class="table table-hover">
<tbody>
<tr id="1" data-sort="1">
<td>One</td>
<td>
<input rownum="1" class="m" />
</td>
</tr>
<tr id="2" data-sort="2">
<td>Two</td>
<td>
<input rownum="2" class="m" />
</td>
</tr>
<tr id="3" data-sort="3">
<td>Three</td>
<td>
<input rownum="3" class="m" />
</td>
</tr>
<tr id="4" data-sort="4">
<td>Four</td>
<td>
<input rownum="4" class="m" />
</td>
</tr>
<tr id="5" data-sort="5">
<td>Five</td>
<td>
<input rownum="5" class="m" />
</td>
</tr>
<tr id="6" data-sort="6">
<td>six</td>
<td>
<input rownum="6" class="m" />
</td>
</tr>
</tbody>
</table>
</div>

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.

take value data & Delete row table with javascript

I have 3 problems with this javascript.
User cant add more item if already limit.
Example max item 3, and value item is ab,bc,cd, how I can take value if using javascript (after all done user will be press submit then all data from table will be post (i cant take data from javascript))?
what I want build is like this : Example 2 item
|Total Item | Name Item | Delete |
| 1 | ABC | DELETE(BUTTON) |
| 2 | CDE | DELETE(BUTTON) |
This is html code, example max item is 6
<table border="0">
<tr>
<td>
Title
</td>
<td>
:
</td>
<td>
<input type="text" name="title" value="" placeholder="Input Title">
</td>
</tr>
<tr>
<td>
Show Item
</td>
<td>
:
</td>
<td>
<select name="max" id="maxitem">
<?php
for($i=1; $i<=6; $i++)
{
echo "<option value=".$i.">".$i." Item</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td>
Product
</td>
<td>
:
</td>
<td>
<input type="text" name="product" id="product" value="" placeholder="Add Product">
</td>
<td>
<input type="button" id="ADD" value="Add Item">
</td>
</tr>
</table>
<table border="1" id="tblname">
<thead>
<tr>
<td>
Total Item
</td>
<td>
Name Item
</td>
<td>
DELETE
</td>
<tr>
</thead>
<tbody>
<tr>
<td>
</td>
</tr>
</tbody>
</table>
<input type="submit" value="SUBMIT">
and this is javascript code :
$(document).ready(function(){
var item = 1;
$('#ADD').click(function(){
var maxitem = parseInt($("#maxitem").val()); //from max item in html
if($('#product').val()){ // check input product
if( item <= maxitem )
{
$('#tblname tbody').append($("#tblname tbody tr:last").clone());
$('#tblname tbody tr:last td:first').val(item);
$('#tblname tbody tr:last td:first').html($('#product').val());
$('#tblname tbody tr:last td:first').append("<input type='button' class='DEL' value='DELETE'>");
var item +=1;
}
else
{
alert ("Max Limit !!!");
}
}else{alert('Enter Text');}
});
// for delete row
$('body').on('click', 'input.DEL', function() {
$(this).parents('tr').remove();
});
});
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(document).ready(function(){
var item = 1;
$('#ADD').click(function(){
var maxitem = parseInt($("#maxitem").val(), 10); //from max item in html
var iCount = 0;
if($('#product').val()){ // check input product
if( item <= maxitem )
{
iCount = $('#tblname tbody tr').length + 1;
szTr = "<tr><td>";
szTr = szTr + iCount + "</td>";
szTr = szTr + "<td>" +$('#product').val() +"</td>";
szTr = szTr + "<td><input type='button' class='DEL' value='DELETE'></td>";
szTr = szTr + "</tr>";
$('#tblname tbody').append(szTr);
item = item+1;
}
else
{
alert ("Max Limit !!!");
}
}else{alert('Enter Text');}
});
// for delete row
$('body').on('click', 'input.DEL', function() {
$(this).parents('tr').remove();
});
$('#get_data').click(function () {
$('#tblname tbody tr').each(function () {
alert($(this).find('td:eq(1)').text());
});
});
});
</script>
</head>
<body>
<table border="0">
<tr>
<td>
Title
</td>
<td>
:
</td>
<td>
<input type="text" name="title" value="" placeholder="Input Title">
</td>
</tr>
<tr>
<td>
Show Item
</td>
<td>
:
</td>
<td>
<select name="max" id="maxitem">
<option value="1">Item1</option>
<option value="2">Item2</option>
<option value="3">Item3</option>
<option value="4">Item4</option>
<option value="5">Item5</option>
<option value="6">Item6</option>
</select>
</td>
</tr>
<tr>
<td>
Product
</td>
<td>
:
</td>
<td>
<input type="text" name="product" id="product" value="" placeholder="Add Product">
</td>
<td>
<input type="button" id="ADD" value="Add Item">
</td>
</tr>
</table>
<table border="1" id="tblname">
<thead>
<tr>
<td>
Total Item
</td>
<td>
Name Item
</td>
<td>
DELETE
</td>
<tr>
</thead>
<tbody>
</tbody>
</table>
<input type="button" value="Get Data" id="get_data">
<input type="submit" value="SUBMIT">
</body>
</html>
See if this is what you are trying to do, your description is hard to decipher:
DEMO: https://jsfiddle.net/d8kpsnxx/
<table border="0">
<tr>
<td>Title</td>
<td>:</td>
<td><input type="text" name="title" value="" placeholder="Input Title"></td>
</tr>
<tr>
<td>Show Item</td>
<td>:</td>
<td>
<select name="max" id="maxitem">
<option value=1>1 Item</option>
<option value=2>2 Item</option>
<option value=3>3 Item</option>
<option value=4>4 Item</option>
<option value=5>5 Item</option>
<option value=6>6 Item</option>
</select>
</td>
</tr>
<tr>
<td>Product</td>
<td>:</td>
<td><input type="text" name="product" id="product" value="" placeholder="Add Product"></td>
<td><input type="button" id="ADD" value="Add Item"></td>
</tr>
</table>
<table border="1" id="tblname">
<thead>
<tr>
<td>
Total Item
</td>
<td>
Name Item
</td>
<td>
DELETE
</td>
<tr>
</thead>
<tbody id="cracker">
</tbody>
</table>
<input id="submitall" type="submit" value="SUBMIT">
<script>
$(document).ready(function() {
var isAllowed = 3;
var isSet = 0;
$(this).on('click',"#ADD",function(e) {
// Prevent submission
e.preventDefault();
// Set all the value object
var drop = $("select[name=max]");
var title = $("input[name=title]");
var prod = $("input[name=product]");
// Append the table
$("#cracker").append('<tr><td>'+title.val()+': '+prod.val()+'</td><td>'+drop.val()+'</td><td><input type="submit" class="dMade" name="'+drop.val()+'" value="DELETE" /></td></tr>');
// Clear all the values to start over
drop.val("");
title.val("");
prod.val("");
// Auto increment
isSet++;
// Turn off/on submit buttons
restFormOpts();
});
$(this).on('click',".dMade",function(e) {
var traversed = $(this).parents("tr");
traversed.remove();
isSet--;
restFormOpts();
});
function restFormOpts()
{
if(isSet === isAllowed) {
$("#ADD").attr("disabled",true);
$("#submitall").attr("disabled",false);
}
else {
$("#ADD").attr("disabled",false);
$("#submitall").attr("disabled",true);
}
}
});
</script>

Skip First Row in html table after javascript

My below code skips the last row of the html table on button click if all the values are filled in the text box's but now i have a situation where i wan to skip the first row only as in my case there will be heading on first row and print all data expect first row.
With Heading demo doent work as there is text on first row
Demo With out heading skips last row working
HTML
<table border="1" id="Positions_names">
<tbody>
<tr>
<td align="center">text heading
</td>
<td>
text heading
</td>
<td style="display:none;">
text heading
</td>
<td style="display:none;">
text heading
</td>
<td style="display:none;">
text heading
</td>
<td style="display:none;">
text heading
</td>
<td style="display:none;">
text heading
</td>
</tr>
<tr>
<td align="center">b
<input type="hidden" value="b">
</td>
<td>
<input onchange="election_title_onchange();" class="designatiom_placeholder" type="text" placeholder="Enter a Designation">
</td>
<td style="display:none;">
<input type="hidden" class="election_id" value="767F1G">
</td>
<td style="display:none;">
<input type="hidden" class="election_title" value="21">
</td>
<td style="display:none;">
<input type="hidden" class="election_date" value="2015-09-21">
</td>
<td style="display:none;">
<input type="hidden" class="election_start_time" value="02:03">
</td>
<td style="display:none;">
<input type="hidden" class="election_end_time" value="15:04">
</td>
</tr>
<tr>
<td align="center">c
<input type="hidden" value="c">
</td>
<td>
<input onchange="election_title_onchange();" class="designatiom_placeholder" type="text" placeholder="Enter a Designation">
</td>
<td style="display:none;">
<input type="hidden" class="election_id" value="767F1G">
</td>
<td style="display:none;">
<input type="hidden" class="election_title" value="21">
</td>
<td style="display:none;">
<input type="hidden" class="election_date" value="2015-09-21">
</td>
<td style="display:none;">
<input type="hidden" class="election_start_time" value="02:03">
</td>
<td style="display:none;">
<input type="hidden" class="election_end_time" value="15:04">
</td>
</tr>
<tr>
<td align="center">d
<input type="hidden" value="d">
</td>
<td>
<input onchange="election_title_onchange();" class="designatiom_placeholder" type="text" placeholder="Enter a Designation">
</td>
<td style="display:none;">
<input type="hidden" class="election_id" value="767F1G">
</td>
<td style="display:none;">
<input type="hidden" class="election_title" value="21">
</td>
<td style="display:none;">
<input type="hidden" class="election_date" value="2015-09-21">
</td>
<td style="display:none;">
<input type="hidden" class="election_start_time" value="02:03">
</td>
<td style="display:none;">
<input type="hidden" class="election_end_time" value="15:04">
</td>
</tr>
</tbody>
</table>
<input type="submit" onclick="save_election_req_details();" id="submit_positions">
js:
$('#submit_positions').click(function () {
var x = document.getElementById("Positions_names").rows.length;
if(x=="1")
{
alert("Select Some Details to Contunue");
}
else {
var html = '';
var arr = [];
var valid = true;
$('#Positions_names tr').each(function (index, me) {
if (index < $('#Positions_names tr').length - 1 && valid) {
var inputs = $('input', me);
inputs.each(function (index, me) {
if ($(me).val().length == 0) valid = false;
});
var selects = $('select', me);
selects.each(function (index, me) {
if ($(me)[0].selectedIndex == 0) valid = false;
});
if (valid){
arr.push('("' + inputs[0].value + '","' + inputs[1].value +'")');
}
}
});
if (valid) {
html = 'INSERT INTO demo (xxxx, xxxxx, xxxx,xxxx,xxxx) VALUES ' + arr.join(',') + ';';
alert(html);
} else
{
alert("Fill the Price or Select the Created Product");
}
}
});
Maybe like this? FIDDLE
I just added another condition in your if-clause.
Before:
if (index < $('#Positions_names tr').length - 1 && valid) {
After:
if (index < $('#Positions_names tr').length && valid && index >= 1) {
Alternatively:
if (index >= 1 && valid) {
try this
$('#Positions_names tr:gt(0)').each(function (index, me) {
$('tbody tr').each(function(){
$(this).find('td:eq(5)').text('$145');
});
In above example you can skip header row by putting it into thead. I have given code to loop through the Table Body
jsFiddle
Some Refrences, may Help you.
each()
find()
:eq() Selector
text()
Depending on how you want to do things. Here is a more succinct way of doing your JavaScript. It uses pseudo elements for first and last. Also you can use <thead> tags to do headers. This eliminates the need to skip the first row.
$('form').submit(function(e) {
//prevents the form from submitting
e.preventDefault();
//pushes the strings into arrays to be joined by commas later
var chunck = [];
//foreach tr in tbody
$('tbody tr')
//do not select first or last child tr
.not(':last-child,:first-child')
//find the inputs an foreach
.find('input').each(function() {
//get the name and the value
var name = $(this).attr("name");
var value = $(this).val();
//if the value is not empty then push it to the string
if (value.length > 0) {
chunck.push("('" + name + "','" + value + "')");
}
})
//chunck.join() puts commas between array elements
var string = 'INSERT INTO (name,value) VALUES ' + chunck.join();
alert(string);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<table border="1">
<thead>
<tr>
<th>Head</th>
<th>Head</th>
</tr>
</thead>
<tbody>
<tr>
<td>a</td>
<td>
<input name='a' />
</td>
</tr>
<tr>
<td>b</td>
<td>
<input name='b' />
</td>
</tr>
<tr>
<td>c</td>
<td>
<input name='c' />
</td>
</tr>
<tr>
<td>d</td>
<td>
<input name='d' />
</td>
</tr>
</tbody>
</table>
<input type="submit" />
</form>

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

Categories