take value data & Delete row table with javascript - 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>

Related

Show values in the html table as json array on button click is not working as expected

User can enter values in some or all the rows present in the html table and click on the submit button. If a value is present in the row (if at least one column field value is entered) and the submit button is clicked, I want to get all the details as a json array.
Working sample demo : http://jsfiddle.net/Crw2C/173/
In the working demo above, when the user clicks on the convert button, the data from the html table is shown as a json array. I tried a similar implementation in my demo as shown in the code below but it is not working as expected.
My sample demo code which is not working as expected: http://plnkr.co/edit/FODEJ1BnhPLGHoH9kjO5?p=preview
Sample html code:
<table id="productTable" border="1">
<tr>
<th>Order ID</th>
<th>Product1</th>
<th>Description</th>
<th>Product2</th>
<th>Comments</th>
</tr>
<tr>
<td><input type="text" name="orderNum" value=""></td>
<td>
<select class="product1" >
<option value=""></option>
</select>
</td>
<td>
<input type="text" name="description" value="">
</td>
.......
Sample js code:
$('#productTable th').each(function(index, item) {
headers[index] = $(item).html();
});
$('#productTable tr').has('td').each(function() {
var arrayItem = {};
$('td', $(this)).each(function(index, item) {
arrayItem[headers[index]] = $(item).html();
});
array.push(arrayItem);
});
Note: With my code above, the entire html element is retrieved and stored as json array but I only want the value. Any sample code would be appreciated as I tried to search and tried in different ways but was unable to succeed. The sample code I tried I also shared in the demo link above, which is not working. Thanks.
You are selecting the whole <td>...</td> instead of this select html input or select elements.
$('#productTable tr').has('td').each(function() {
var arrayItem = {};
$('td input, td select', $(this)).each(function(index) {
arrayItem[headers[index]] = $(this).val();
});
array.push(arrayItem);
});
Check below snippet.
function populateSelect() {
var ids = [{"pid":"laptop","des":"laptop"},{"pid":"Mobile","des":"Mobile"},{"pid":"IPAD mini.","des":"IPAD mini."}]
var productDropdown1 = $(".product1");
var productDropdown2 = $(".product2");
$.each(ids, function(index,value) {
$("<option />").text(value.des).val(value.pid).appendTo(productDropdown1);
$("<option />").text(value.des).val(value.pid).appendTo(productDropdown2);
});
$("select").change(function() {
var row = $(this).closest("tr");
var product1_drop = $('.product1',row).val();
var product2_drop = $('.product2',row).val();
var descValue = $('input[name="description"]',row).val();
if( product1_drop && product2_drop)
validate(product1_drop,product2_drop, descValue);
});
$('input[name="description"]').on('input', function(e){
var row = $(this).closest("tr");
var product1_drop = $('.product1',row).val();
var product2_drop = $('.product2',row).val();
console.log("-inut -product1_drop----- " + product1_drop);
if( product1_drop && product2_drop)
validate(product1_drop,product2_drop, $(this).val());
});
}
function validate(prod1, prod2, desc){
if(desc && prod1 === prod2 ){
alert('Product1 and Product2 cannot have same value');
}
}
function submitData(){
alert("submit");
var array = [];
var headers = [];
$('#productTable th').each(function(index, item) {
headers[index] = $(item).html();
});
$('#productTable tr').has('td').each(function() {
var arrayItem = {};
$('td input, td select', $(this)).each(function(index) {
arrayItem[headers[index]] = $(this).val();
});
array.push(arrayItem);
});
alert(JSON.stringify(array));
}
$(document).ready(function(){
populateSelect();
// $('#productTable tbody tr:gt(0) :input').prop('disabled',true)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="productTable" border="1">
<tr>
<th>Order ID</th>
<th>Product1</th>
<th>Description</th>
<th>Product2</th>
<th>Comments</th>
</tr>
<tr>
<td><input type="text" name="orderNum" value=""></td>
<td>
<select class="product1" >
<option value=""></option>
</select>
</td>
<td>
<input type="text" name="description" value="">
</td>
<td>
<select class="product2" >
<option value=""></option>
</select>
</td>
<td>
<input type="text" name="Comments" value="">
</td>
</tr>
<tr>
<td><input type="text" name="orderNum" value=""></td>
<td>
<select class="product1" >
<option value=""></option>
</select>
</td>
<td>
<input type="text" name="description" value="">
</td>
<td>
<select class="product2" >
<option value=""></option>
</select>
</td>
<td>
<input type="text" name="Comments" value="">
</td>
</tr>
<tr>
<td><input type="text" name="orderNum" value=""></td>
<td>
<select class="product1" >
<option value=""></option>
</select>
</td>
<td>
<input type="text" name="description" value="">
</td>
<td>
<select class="product2" >
<option value=""></option>
</select>
</td>
<td>
<input type="text" name="Comments" value="">
</td>
</tr>
<tr>
<td><input type="text" name="orderNum" value=""></td>
<td>
<select class="product1" >
<option value=""></option>
</select>
</td>
<td>
<input type="text" name="description" value="">
</td>
<td>
<select class="product2" >
<option value=""></option>
</select>
</td>
<td>
<input type="text" name="Comments" value="">
</td>
</tr>
</table> <br>
<input type="submit" value="submit" onclick="submitData()">
In your column loop, you don't want to assign the entire html of the cell. Rather, you need just the value of the select box that is contained in the cell.
In other words: change $(item).html() in your loop on the 'td's to $(item).find('select').val().
You should change this part of code
$('#productTable tr').has('td').each(function() {
var arrayItem = {};
$('td input, td select', $(this)).each(function(index, item) {
arrayItem[headers[index]] = $(item).val();
});
array.push(arrayItem);
});
You are selecting the <td> html, but what you really want is the input and select values.

cannot fill value to <input> using jquery

I have this html
<table id="tabel-item-borrowed" class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th class="headtabel">Categories</th>
<th class="headtabel">Description</th>
<th class="headtabel">Action</th>
</tr>
</thead>
<tbody>
<tr id="t11">
<td>
<input id="categories[1]" type="text" name="categories1" size="40">
</td>
<td>
<input id="description[1]" type="text" name="description1" size="40">
</td>
<td>
<input id="delete[1]" type="button" name="delete" value="delete" size="5">
</td>
</tr>
<tr id="t12">
<td>
<input id="categories[2]" type="text" name="categories2" size="40">
</td>
<td>
<input id="description[2]" type="text" name="description2" size="40">
</td>
<td>
<input id="delete[2]" type="button" name="delete" value="delete" size="5">
</td>
</tr>
</tbody>
</table>
html code inside tbody tag is generated by javascript, after generate the code I want to fill the value inside #categories[], #description[] ids
this my javascript code to fill the value
//button simpan item
$('#bSimpanItem').click(function () {
var addnum = $('input#iduser').val();
var addposinfo = $('input#idposinfo').val();
if (addposinfo == '0') {
messageAlert('[ ERROR ]<br>You must completely fill position info field.', 'error');
} else {
var lastrow = ( $('#lastrow').val() ) ? parseInt($('#lastrow').val()) : 1;
var row = parseInt($('#comboqty').val());
var category = $('#combocategory1').val() +'-'+ $('#combocategory2').val();
var description = $('#borrowdesc').val();
addNewRow(row);
console.log(' last row ' + lastrow);
console.log(' total row ' + row);
console.log(' category '+category);
console.log(' description '+description);
for (var i = 1 ; i <= row; i++) {
console.log("index " + i);
$('input#idposinfo').val('');
//fill value "111" and "222" inside <input id="categories[1]"> and <input id="description[1]">
$("input#categories["+lastrow+"]").val("111");
$("input#description["+lastrow+"]").val("222");
lastrow++;
document.getElementById('lastrow').value = lastrow;
console.log("success run bSimpan inside for");
}
console.log("success run bSimpan outside for");
resetForm('formBorrowItem');
$('#formBorrowItem').hide();
//return false;
}
});
but nothing was shown inside the input value
[xxxx] is an attribute selector. If the id has them in the value, you need to escape them as stated in the jQuery documentation.
$("input#categories\\["+lastrow+"\\]");
Try this
$("input#categories\\["+lastrow+"\\]").val("111");
$("input#description\\["+lastrow+"\\]").val("222");
Html code
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('#bSimpanItem').click(function () {
var iIndex = 0;
$('#tabel-item-borrowed tbody tr').each(function (index) {
iIndex = index + 1
$(this).find("td:eq(0)").find('#categories\\[' + iIndex + '\\]').val('111');
$(this).find("td:eq(1)").find('#description\\[' + iIndex + '\\]').val('22');
});
});
});
</script>
</head>
<body style="width:50%;">
<input type="button" value="bSimpanItem" id="bSimpanItem"/>
<table id="tabel-item-borrowed" class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th class="headtabel">Categories</th>
<th class="headtabel">Description</th>
<th class="headtabel">Action</th>
</tr>
</thead>
<tbody>
<tr id="t11">
<td>
<input id="categories[1]" type="text" name="categories1" size="40">
</td>
<td>
<input id="description[1]" type="text" name="description1" size="40">
</td>
<td>
<input id="delete[1]" type="button" name="delete" value="delete" size="5">
</td>
</tr>
<tr id="t12">
<td>
<input id="categories[2]" type="text" name="categories2" size="40">
</td>
<td>
<input id="description[2]" type="text" name="description2" size="40">
</td>
<td>
<input id="delete[2]" type="button" name="delete" value="delete" size="5">
</td>
</tr>
</tbody>
</table>
</body>
</html>
You can access the input inside the loop like this:
$('input[id="categories[' + lastrow + ']"]').val("111");

Calculate Total value for two input fields based on items selected from a select option tag in table

I want to get the value of the Amount pass to either Debit Amount or Credit Amount base on the Type selected if DR is select, then the value should be pass to Debit Amount and if CR is selected, then the value should be pass to Credit Amount. Total Amount should be passed in case of multiple Type options are selected
The HTML
<div>
<label style="margin-bottom:3px;">Debit Amount</label><span>
<input type="text" name="total_debit" id="totalDebit"/></span>
</div>
<div>
<label>Credit Amount</label><span>
<input type="text" name="total_credit" id="totalCredit" /></span>
</div>
<table class="table-bordered table-hover">
<thead>
<tr>
<th width="2%"><input id="check_all" type="checkbox"/></th>
<th width="5%">Type</th>
<th width="5%">Account Code</th>
<th width="15%">Account Name</th>
<th width="10%">Fund</th>
<th width="10%">Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td><input class="case" type="checkbox"/></td>
<td><select name="account_id[]" class=" mySelect" id="type_1">
<option value="000"></option>
<option value="1">DR</option>
<option value="2">CR</option>
</select>
</td>
<td>
<input type="text" name="accountCode[]" id="accountCode_1">
</td>
<td>
<input type="text" name="accountName[]" id="accountName_1"></td>
<td>
<select name="fund_id[]" >
<option></option>
</select>
</td>
<td>
<input type="text" name="amount[]" id="amount_1" class="totalLineAmount">
</td>
</tr>
<tr>
<td><input class="case" type="checkbox"/></td>
<td><select name="account_id[]" class=" mySelect" id="type_2">
<option value="000"></option>
<option value="1">DR</option>
<option value="2">CR</option>
</select>
</td>
<td>
<input type="text" name="accountCode[]" id="accountCode_2">
</td>
<td>
<input type="text" name="accountName[]" id="accountName_2"></td>
<td>
<select name="fund_id[]" >
<option></option>
</select>
</td>
<td>
<input type="text" name="amount[]" id="amount_2" class="totalLineAmount">
</td>
</tr>
<tr>
<td><input class="case" type="checkbox"/></td>
<td><select name="account_id[]" class=" mySelect" id="type_3">
<option value="000"></option>
<option value="1">DR</option>
<option value="2">CR</option>
</select>
</td>
<td>
<input type="text" name="accountCode[]" id="accountCode_3">
</td>
<td>
<input type="text" name="accountName[]" id="accountName_3"></td>
<td>
<select name="fund_id[]" >
<option></option>
</select>
</td>
<td>
<input type="text" name="amount[]" id="amount_3" class="totalLineAmount">
</td>
</tr>
<tr>
<td><input class="case" type="checkbox"/></td>
<td><select name="account_id[]" class=" mySelect" id="type_4">
<option value="000"></option>
<option value="1">DR</option>
<option value="2">CR</option>
</select>
</td>
<td>
<input type="text" name="accountCode[]" id="accountCode_4">
</td>
<td>
<input type="text" name="accountName[]" id="accountName_4"></td>
<td>
<select name="fund_id[]" >
<option></option>
</select>
</td>
<td>
<input type="text" name="amount[]" id="amount_4" class="totalLineAmount">
</td>
</tr>
</tbody>
</table>
Jquery Script
<script>
$(function(){
$(document).on("change",".mySelect",function(e){
e.preventDefault();
var _this=$(this);
var id =_this.val();
if ( id == 1) {
calculateTotalDebit();
}else if (id == 2) {
calculateTotalCredit();
}
function calculateTotalDebit(){
total = 0;
$('.totalLineAmount').each(function(){
if($(this).val() != '' )total += parseFloat( $(this).val() );
$('#totalDebit').val( total.toFixed(2) );
});
}
function calculateTotalCredit(){
total = 0;
$('.totalLineAmount').each(function(){
if($(this).val() != '' )total += parseFloat( $(this).val() );
});
$('#totalCredit').val( total.toFixed(2) );
}
});
});
</script>
$('.totalLineAmount') is selecting all of the amount inputs, so the calculateTotalDebit and calculateTotalCredit functions are adding them all regardless of the DR/CR type. You can check for the type inside the functions, for calculateTotalDebit for example:
function calculateTotalDebit(){
var total = 0;
$('.totalLineAmount').each(function(){
var thisNumber = $(this).attr('id').slice(-1);
// select the type of this amount
var type = $('#type_' + thisNumber);
// add only if the type is DR (val == 1)
if($(this).val() != '' && type.val() == 1)total += parseFloat( $(this).val() );
$('#totalDebit').val( total.toFixed(2) );
});
$(function() {
$(document).on("change", ".mySelect", function(e) {
e.preventDefault();
var _this = $(this);
var id = _this.val();
if (id == 1) {
calculateTotalDebit();
} else if (id == 2) {
calculateTotalCredit();
}
function calculateTotalDebit() {
total = 0;
$('.totalLineAmount').each(function() {
var thisNumber = $(this).attr('id').slice(-1);
// select the type of this amount
var type = $('#type_' + thisNumber);
// add only if the type is DR (val == 1)
if ($(this).val() != '' && type.val() == 1) total += parseFloat($(this).val());
$('#totalDebit').val(total.toFixed(2));
});
}
function calculateTotalCredit() {
total = 0;
$('.totalLineAmount').each(function() {
var thisNumber = $(this).attr('id').slice(-1);
// select the type of this amount
var type = $('#type_' + thisNumber);
// add only if the type is CR (val == 2)
if ($(this).val() != '' && type.val() == 2) total += parseFloat($(this).val());
});
$('#totalCredit').val(total.toFixed(2));
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<label style="margin-bottom:3px;">Debit Amount</label><span>
<input type="text" name="total_debit" id="totalDebit"/></span>
</div>
<div>
<label>Credit Amount</label><span>
<input type="text" name="total_credit" id="totalCredit" /></span>
</div>
<table class="table-bordered table-hover">
<thead>
<tr>
<th width="2%">
<input id="check_all" type="checkbox" />
</th>
<th width="5%">Type</th>
<th width="5%">Account Code</th>
<th width="15%">Account Name</th>
<th width="10%">Fund</th>
<th width="10%">Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input class="case" type="checkbox" />
</td>
<td>
<select name="account_id[]" class=" mySelect" id="type_1">
<option value="000"></option>
<option value="1">DR</option>
<option value="2">CR</option>
</select>
</td>
<td>
<input type="text" name="accountCode[]" id="accountCode_1">
</td>
<td>
<input type="text" name="accountName[]" id="accountName_1">
</td>
<td>
<select name="fund_id[]">
<option></option>
</select>
</td>
<td>
<input type="text" name="amount[]" id="amount_1" class="totalLineAmount">
</td>
</tr>
<tr>
<td>
<input class="case" type="checkbox" />
</td>
<td>
<select name="account_id[]" class=" mySelect" id="type_2">
<option value="000"></option>
<option value="1">DR</option>
<option value="2">CR</option>
</select>
</td>
<td>
<input type="text" name="accountCode[]" id="accountCode_2">
</td>
<td>
<input type="text" name="accountName[]" id="accountName_2">
</td>
<td>
<select name="fund_id[]">
<option></option>
</select>
</td>
<td>
<input type="text" name="amount[]" id="amount_2" class="totalLineAmount">
</td>
</tr>
<tr>
<td>
<input class="case" type="checkbox" />
</td>
<td>
<select name="account_id[]" class=" mySelect" id="type_3">
<option value="000"></option>
<option value="1">DR</option>
<option value="2">CR</option>
</select>
</td>
<td>
<input type="text" name="accountCode[]" id="accountCode_3">
</td>
<td>
<input type="text" name="accountName[]" id="accountName_3">
</td>
<td>
<select name="fund_id[]">
<option></option>
</select>
</td>
<td>
<input type="text" name="amount[]" id="amount_3" class="totalLineAmount">
</td>
</tr>
<tr>
<td>
<input class="case" type="checkbox" />
</td>
<td>
<select name="account_id[]" class=" mySelect" id="type_4">
<option value="000"></option>
<option value="1">DR</option>
<option value="2">CR</option>
</select>
</td>
<td>
<input type="text" name="accountCode[]" id="accountCode_4">
</td>
<td>
<input type="text" name="accountName[]" id="accountName_4">
</td>
<td>
<select name="fund_id[]">
<option></option>
</select>
</td>
<td>
<input type="text" name="amount[]" id="amount_4" class="totalLineAmount">
</td>
</tr>
</tbody>
</table>
I guess you have to update both "Debit Amount" and "Credit Amount" boxes, so you have to call both functions each time. It may be better to merge both functions into one calculateAmounts function. I'd also add event listeners to the .totalLineAmount boxes to update the totals automatically.
Try this code instead (demo):
$(function() {
function calculateTotals() {
var DRTotal = 0,
CRTotal = 0;
$('.totalLineAmount').each(function() {
var $this = $(this),
val = $this.val() || 0,
type = $this.closest('tr').find('.mySelect').val();
if (val && type === "1") {
DRTotal += parseFloat(val);
} else if (val && type === "2") {
CRTotal += parseFloat(val);
}
});
$('#totalDebit').val(DRTotal.toFixed(2));
$('#totalCredit').val(CRTotal.toFixed(2));
}
$(document).on("change", ".mySelect, .totalLineAmount", function(e) {
e.preventDefault();
calculateTotals();
});
});
In my opinion, you should add event listener on each input, calculate and put proper data into total amount in your callback function like
$('.myInputClass').on('change', function() {
// your code here..
updateAmountField(amount);
});
function updateAmountField(amount) {
$('.myTotalAmountInput').value(amount);
}

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>

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