Get all values per table column dynamically using javascript or jquery - javascript

I need to get all values per column dynamically and save it using JS or Jquery. I have a photo here so that you guys can visualize what I am trying to do. Please see the image.
Sad to say this is as far as I can go. I cant seems to get what I realy want to achieve. Just a beginner here.
$(function() {
$('#add_supplier').click(function() {
$('#supplier_table > thead > tr#first-header').append(
'<th colspan="2" class="supplier_name"><input type="text" class="form-control" placeholder="Enter Supplier" style="text-align: center;"></th>'
);
$('#supplier_table > thead > tr#second-header').append(
'<th>Price</th>' +
'<th>Total</th>'
);
$('#supplier_table > tbody > tr').not('#totals,#tr-td-2').append(
'<td class="ignore"><input type="text" class="form-control price text-right" ></td>' +
'<td><input type="text" class="form-control total text-right" readonly></td>'
);
$('#supplier_table > tbody > #totals').not('#tr-td-2').append(
'<td class="ignore"><input class="form-control" disabled></td>' +
'<td><input type="text" class="form-control grandtotal text-right" readonly=""></td>'
);
$('#supplier_table > tbody > #tr-td-2').append(
'<td colspan="2" style="width: 160px;"><input style="text-align: center;" class="form-control" type="text"></td>'
);
//
refresh_index();
//
});
$('#add_terms').click(function() {
var $tableBody = $('#supplier_table').find("tbody").not('#totals'),
$trLast = $tableBody.find("tr:last"),
$trNew = $trLast.clone();
$trNew.find('input').val('');
$trLast.after($trNew);
refresh_index();
});
// $('#add_supplier').click();
$('#add_item').click(function() {
$('#supplier_table > tbody').not('#totals, #tr-td-2').append(
// $("#supplier_table tbody tr:last").clone()
'<tr class="tbody-tr">' +
'<td class="ignore"><input type="text" class="form-control " value="Monitor" readonly=""></td>' +
'<td class="ignore"><input type="text" class="form-control qty" value="30" readonly=""></td>' +
'<td class="ignore"><input type="text" class="form-control price"></td>' +
'<td><input type="text" class="form-control total for_sum-1" readonly=""></td>' +
'</tr>'
);
//
refresh_index();
//
});
//
function refresh_index() {
$('.price').each(function(i) {
i++;
$(this).attr('id', 'price-' + i);
$(this).attr('data-num', i);
event_handler();
});
$('.total').each(function(i) {
i++;
$(this).attr('id', 'total-' + i);
});
$('.qty').each(function(i) {
i++;
$(this).attr('id', 'qty-' + i);
});
$('.grandtotal').each(function(i) {
i++;
$(this).attr('id', 'grandtotal-' + i);
});
$('.supplier_name').each(function(i) {
i++;
$(this).attr('id', 'supplier_name-' + i);
});
}
refresh_index();
//
//
function event_handler() {
$('.price').unbind('keyup').bind('keyup', function() {
var id = this.id;
var num = id.split('-');
var pos = $(this).closest('tr').index() + 1;
var qty = $('#qty-' + pos).val();
var price = $(this).val();
var total = parseFloat(qty) * parseFloat(price);
if (isNaN(total)) {
var total = 0;
}
$('#total-' + num[1]).text(total);
$('#total-' + num[1]).val(total);
var num_of_supplier_name = $('.supplier_name').length;
sum_of_total();
});
}
function sum_of_total() {
// var sum = 0;
// //iterate through each textboxes and add the values
// $(".total").each(function () {
// //add only if the value is number
// if (!isNaN($(this).val()) && $(this).val().length != 0) {
// sum += parseFloat(this.value);
// }
// });
// //.toFixed() method will roundoff the final sum to 2 decimal places
// $("#grandtotal-"+num).val(sum);
var totals = [];
$('#tb').find('tr').each(function() {
var $row = $(this);
$row.children('td').not('.ignore').each(function(index) {
totals[index] = totals[index] || 0;
totals[index] += parseInt($(this).text()) || 0;
});
})
$('#totals td').not('.ignore').each(function(index) {
// $(this).text(totals[index]);
var id = index + 1;
$('#grandtotal-' + id).val(totals[index]);
});
$("#tb").on("click", "tr", function() {
$(this).find("td").slice(0, 4).prop("contenteditable", true);
});
// var max = 0;
// $('.grandtotal').each(function()
// {
// $this = parseInt( $(this).val() );
// // console.log($this);
// if ($this > max) {
// max = $this;
// }
// // $('.grandtotal').val(max).css('background-color','yellow');
// // console.log('Lowest Offer : '+max);
// });
// console.log('Lowest Offer : '+max);
// var high = Math.min.apply(Math, $('.grandtotal').map(function(){
// return $(this).val()
// }))
// console.log('Lowest Offer : '+high);
var vals = $('.grandtotal').map(function() {
return parseInt($(this).val(), 10) ? parseInt($(this).val(), 10) : null;
}).get();
// then find their minimum
var min = Math.min.apply(Math, vals);
console.log(min);
// tag any cell matching the min value
$('.grandtotal').filter(function() {
// return parseInt($(this).val(), 10) === min;
if (parseInt($(this).val(), 10) === min) {
$(this).css("background-color", "#dff0d8");
} else {
$(this).css("background-color", "transparent");
}
});
}
//
});
<button type="button" class="btn btn-success" id="add_supplier">Add Supplier</button>
<!-- <button type="button" class="btn btn-default" id="add_item">Add Item</button> -->
<button type="button" class="btn btn-primary" id="add_terms">Add Terms</button>
<table class="table table-bordered" id="supplier_table">
<thead>
<tr id="first-header">
<th></th>
<th></th>
<th colspan="2" class="supplier_name" id="supplier_name-1"><input type="text" class="form-control" placeholder="Enter Supplier" style="text-align: center;"></th>
</tr>
<tr id="second-header">
<th>Item</th>
<th>Qty</th>
<th>Price</th>
<th>Total</th>
</tr>
</thead>
<tbody id="tb">
<tr class="tbody-tr">
<td class="ignore"><input type="text" class="form-control" value="Mouse" readonly=""></td>
<td class="ignore"><input type="text" class="form-control qty" value="10" readonly=""></td>
<td class="ignore"><input type="text" class="form-control price"></td>
<td><input type="text" class="form-control total for_sum-1" readonly=""></td>
</tr>
<tr class="tbody-tr">
<td class="ignore"><input type="text" class="form-control" value="Keyboard" readonly=""></td>
<td class="ignore"><input type="text" class="form-control qty" value="20" readonly=""></td>
<td class="ignore"><input type="text" class="form-control price"></td>
<td><input type="text" class="form-control total for_sum-1" readonly=""></td>
</tr>
<tr class="tbody-tr">
<td class="ignore"><input type="text" class="form-control " value="Monitor" readonly=""></td>
<td class="ignore"><input type="text" class="form-control qty" value="30" readonly=""></td>
<td class="ignore"><input type="text" class="form-control price"></td>
<td><input type="text" class="form-control total for_sum-1" readonly=""></td>
</tr>
<tr id="totals">
<td class="ignore"></td>
<td class="ignore"></td>
<td class="ignore"><input class="form-control" disabled value="Grand Total : " style="text-align: right;"></td>
<td><input type="text" class="form-control grandtotal text-right" readonly=""></td>
</tr>
<tr id="tr-td-2">
<td>
<p style="width: 60px;"></p>
</td>
<td><input style="font-weight: bold; text-align: right;" type="text" class="form-control" placeholder="Enter terms"></td>
<!-- <td ><p style="width: 60px;"></p></td> -->
<td colspan="2" style="width: 160px;"><input style="text-align: center;" class="form-control" type="text"></td>
</tr>
</tbody>
</table>
Actual Demo Link
JSFIDDLE

Related

Autonumbering is not working on added rows

I have 2 functions. Add dynamic rows and Autonumbering. My problem is, my autonumbering is not working on my dynamically added rows. I wonder what could be the problem? The "class="form-control" is all the same for my input type field. However, it is still not working. I have provided my js fiddle below.
https://prnt.sc/124vuju
https://jsfiddle.net/rain0221/59k4c0yg/3/ // in "lb" column, type any number and hit ctrl+enter in order to do autonumbering
//this is my function for autonumbering
const inputs = document.querySelectorAll(".form-control");
inputs[0].addEventListener("keyup", e => {
let value = parseInt(e.target.value);
if ((e.ctrlKey || e.metaKey) && (e.keyCode == 13 || e.keyCode == 10)) {
inputs.forEach((inp, i) => {
if (i !== 0) {
inp.value = ++value;
}
})
}
})
//this is my function for adding dynamic rows.
$("#addrow").on('click', function() {
let rowIndex = $('.auto_num').length + 1;
let rowIndexx = $('.auto_num').length + 1;
var newRow = '<tr><td><input class="auto_num" type="text" value="' + rowIndexx + '" /></td>"' +
'<td><input name="lightBand' + rowIndex + '" id="auto" value="" class="form-control" type="number" readonly /></td>"' +
'<td><input id="weight' + rowIndex + '" name="weight' + rowIndex + '" type="number" /></td>"' +
'<td><input id="wingBand' + rowIndex + '" name="wingBand' + rowIndex + '" type="number" /></td>"' +
'<td><input type="button" class="removerow" id="removerow' + rowIndex + '" name="removerow' + rowIndex + '" value="Remove"/></td>';
$("#applicanttable > tbody > tr:last").after(newRow);
});
$(document).on('click', '.removerow', function() {
$(this).parents('tr').remove();
regenerate_auto_num();
});
function regenerate_auto_num() {
let count = 1;
$(".auto_num").each(function(i, v) {
$(this).val(count);
count++;
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered" border="1" id="applicanttable">
<thead>
<tr>
</tr>
</thead>
<tbody>
<div class="row">
<tr>
<th>#</th>
<th>LB#</th>
<th>Weight#</th>
<th>Wingband #</th>
<th>Action</th>
</tr>
<tr id="row_0">
<td>
<input id="#" name="#" class="auto_num" type="text" value="1" readonly />
</td>
<td class="labelcell">
<input value="" class="hehe form-control" placeholder="" required id="auto" />
</td>
<td class="labelcell">
<input name="weight" class="hehe form-control" type="number" />
</td>
<td class="labelcell">
<input name="wingBand" class="hehe form-control" type="number" />
</td>
<td class="labelcell">
<input type="button" class="removerow" id="removerow0" name="removerow0" value="Remove">
</td>
</tr>
</div>
</tbody>
</div>
<tfoot>
<tr>
</tr>
<tr>
<button type="button" id="addrow" style="margin-bottom: 1%;">Add Row</button>
</tr>
</tfoot>
</table>
You need to find the elements inside eventListener event. Since you are finding the element global onload so if will not hold the elements added dynamically. You can move the blow code inside addEventListener keyup event.
const inputs = document.querySelectorAll(".form-control");
To attach the keyup event, you can use document.querySelectorAll(".form-control")[0] instead of inputs[0].
document.querySelectorAll(".form-control")[0].addEventListener("keyup", e => {
const inputs = document.querySelectorAll(".form-control");
let value = parseInt(e.target.value);
if ((e.ctrlKey || e.metaKey) && (e.keyCode == 13 || e.keyCode == 10)) {
inputs.forEach((inp, i) => {
if (i !== 0) {
inp.value = ++value;
}
})
}
});
I can see that you have assigned the 'form-control' class only for LB# column so autonumber will be generate only for LB#. In case you want to generate autonumber for all the columns, assign the class="form-control" to each added dynamically.
The problem is that you are addding keyup listeners only to those elements that are already present in the DOM at the time you are adding them.
What you need instead is called delegate listeners, and it means that you rely on the mechanism that most events bubble up in the DOM, allowing you to attach the keyup listener to an element that is an ancestor to all the input elements of interest.
Inside that listener, you then check if the element they event came from is one you want to handle.
//this is my function for autonumbering
const inputAncestor = document.querySelector("tbody");
inputAncestor.addEventListener("keyup", e => {
if (
e.target.matches('input.form-control') &&
((e.ctrlKey || e.metaKey) && (e.keyCode == 13 || e.keyCode == 10))
) {
const inputs = document.querySelectorAll(".form-control");
let value = parseInt(e.target.value);
inputs.forEach((inp) => {
if (inp !== e.target) {
inp.value = ++value;
}
})
}
})
//this is my function for adding dynamic rows.
$("#addrow").on('click', function() {
let rowIndex = $('.auto_num').length + 1;
let rowIndexx = $('.auto_num').length + 1;
var newRow = '<tr><td><input class="auto_num" type="text" value="' + rowIndexx + '" /></td>"' +
'<td><input name="lightBand' + rowIndex + '" value="" class="form-control" type="number" readonly /></td>"' +
'<td><input id="weight' + rowIndex + '" name="weight' + rowIndex + '" type="number" /></td>"' +
'<td><input id="wingBand' + rowIndex + '" name="wingBand' + rowIndex + '" type="number" /></td>"' +
'<td><input type="button" class="removerow" id="removerow' + rowIndex + '" name="removerow' + rowIndex + '" value="Remove"/></td>';
$("#applicanttable > tbody > tr:last").after(newRow);
});
$(document).on('click', '.removerow', function() {
$(this).parents('tr').remove();
regenerate_auto_num();
});
function regenerate_auto_num() {
let count = 1;
$(".auto_num").each(function(i, v) {
$(this).val(count);
count++;
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered" border="1" id="applicanttable">
<thead>
<tr>
<th>#</th>
<th>LB#</th>
<th>Weight#</th>
<th>Wingband #</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr id="row_0">
<td>
<input id="#" name="#" class="auto_num" type="text" value="1" readonly />
</td>
<td class="labelcell">
<input value="" class="hehe form-control" placeholder="" required id="auto" />
</td>
<td class="labelcell">
<input name="weight" class="hehe form-control" type="number" />
</td>
<td class="labelcell">
<input name="wingBand" class="hehe form-control" type="number" />
</td>
<td class="labelcell">
<input type="button" class="removerow" id="removerow0" name="removerow0" value="Remove">
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan=5><button type="button" id="addrow" style="margin-bottom: 1%;">Add Row</button>
</tr>
</tfoot>
</table>
Unfortunately, your code has several more problems, which I tried to fix.
As mentioned in the first comment to your question, you cannot have a div as a child of tbody. Only tr is allowed here.
You are using duplicate id value auto. That is invalid HTML.
In your markup, you have the class form-control on all the inputs. In your dynamically added markup it's only on the first input. Which version is the correct one?
In your tfoot you had the button as direct child. This is, again, invalid HTML. The only child element(s) tfoot can have is tr.
The very first row in your table describes the columns and acts as your table's header, yet it did not reside in the thead part of your table.

I want to combine 2 different java scripts

I have 2 java script codes, one work as a search suggestion and second is for adding another form fields dynamically and this second script also calculate values given in input fields, but both scripts have this 'ADD MORE PRODUCT' feature. What i want is; i want to combine both 'ADD more" feature, because 1st script works on id="" tag to identify field to show search result but second script not do it.
Fetching details in first row is successful, but when i click ADD more button populated by second script, it does not work
//Script to fetch details based on search box :
$(document).ready(function() {
$(document).on('keydown', '.prname', function() {
var id = this.id;
var splitid1 = id.split('_');
var index1 = splitid1[1];
$('#' + id).autocomplete({
source: function(request, response) {
$.ajax({
url: "getDetails.php",
type: 'post',
dataType: "json",
data: {
search: request.term,
request: 3
},
success: function(data) {
response(data);
}
});
},
select: function(event, ui) {
$(this).val(ui.item.label); // display the selected text
var prid = ui.item.value; // selected id to input
// AJAX
$.ajax({
url: 'getDetails.php',
type: 'post',
data: {
prid: prid,
request: 4
},
dataType: 'json',
success: function(response) {
var len = response.length;
if (len > 0) {
var id = response[0]['id'];
var fprice = response[0]['fprice'];
var packing = response[0]['packing'];
var pweight = response[0]['pweight'];
document.getElementById('fprice_' + index1).value = fprice;
document.getElementById('packing_' + index1).value = packing;
document.getElementById('pweight_' + index1).value = pweight;
}
}
});
return false;
}
});
});
// Add more
$('#addmore').click(function() {
// Get last id
var lastname_id = $('.tr_input input[type=text]:nth-child(1)').last().attr('id');
var split_id = lastname_id.split('_');
// New index
var index = Number(split_id[1]) + 1;
// Create row with input elements
var html = "<tr class='tr_input'><td><input type='text' class='name' id='name_" + index + "' placeholder='Enter name'></td><td><input type='text' class='phone' id='phone_" + index + "' ></td><td><input type='text' class='address' id='address_" + index + "' ></td><td><input type='text' class='custid' id='custid_" + index + "' ></td></tr>";
// Append data
$('tbody').append(html);
});
});
// Second script to do calculation :
$(document).ready(function() {
var i = 1;
$("#add_row").click(function() {
b = i - 1;
$('#addr' + i).html($('#addr' + b).html()).find('td:first-child').html(i + 1);
$('#tab_logic').append('<tr id="addr' + (i + 1) + '"></tr>');
i++;
});
$("#delete_row").click(function() {
if (i > 1) {
$("#addr" + (i - 1)).html('');
i--;
}
calc();
});
$('#tab_logic tbody').on('keyup change', function() {
calc();
});
$('#tax').on('keyup change', function() {
calc_total();
});
});
function calc() {
$('#tab_logic tbody tr').each(function(i, element) {
var html = $(this).html();
if (html != '') {
var qty = $(this).find('.qty').val();
var price = $(this).find('.fprice').val();
var discount = $(this).find('.discount').val();
$(this).find('.total').val((qty * price) - discount);
calc_total();
}
});
}
function calc_total() {
total = 0;
$('.total').each(function() {
total += parseInt($(this).val());
});
$('#sub_total').val(total.toFixed(2));
tax_sum = total / 100 * $('#tax').val();
$('#tax_amount').val(tax_sum.toFixed(2));
$('#total_amount').val((tax_sum + total).toFixed(2));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<table class="table table-bordered table-hover" style='border-collapse: collapse;' id="tab_logic">
<thead>
<tr>
<th class="text-center">#</th>
<th class="text-center"> Product </th>
<th width="190px" class="text-center"> Price </th>
<th width="30px" class="text-center"> Price for </th>
<th width="100px" class="text-center"> Packing </th>
<th width="80px" class="text-center"> Qty </th>
<th width="100px" class="text-center"> Discount </th>
<th width="150px" class="text-center"> Total </th>
</tr>
</thead>
<tbody>
<tr class='tr_input' id='addr0'>
<td>1</td>
<td><input type="text" name='product[]' id="prname_1" class="prname form-control" /></td>
<td>
<input type="number" name='price[]' id='fprice_1' class="form-control fprice price" step="0.00" min="0" />
</td>
<td><input style="width:70px" type="text" class="pweight input-group-text" id="pweight_1"></td>
<td><input type="text" name='pack[]' class="form-control packing" id='packing_1' step="0" min="0" /></td>
<td><input type="text" name='qty[]' class="form-control qty" id="qty_1" step="0" min="0" /></td>
<td><input type="text" name='discount[]' class="form-control discount" id="discount_1" step="0.00" min="0" /></td>
<td><input type="number" name='total[]' class="form-control total" id="total_1" readonly/></td>
</tr>
<tr id='addr1'></tr>
</tbody>
</table>

(CLOSED) When button is clicked, How to Get input values in the 1st table row and display them in the newly added rows

Now, when the ok button is clicked, additional rows will be added below the 1st table row. I'm wondering when the button is clicked,how to get the values from the 1st table row, and add those values to the row(s) newly added (possibly more than 1 row depends on how many row(s) user input.
Desired result
No Tommy Danvers
1 Tommy Danvers
2 Tommy Danvers
3 Tommy Danvers
$('#add-row').click(function() {
var $tbody, $row, additionalRows;
var numNewRows = parseInt($('#insert-rows-amnt').val(), 10);
if (isNaN(numNewRows) || numNewRows <= 0) {
alert('Please enter number of row');
} else {
$tbody = $('table#one tbody ');
$row = $tbody.find('tr:last');
var lastRowIndex = ($row.index() == -1 ? 0 : $row.index()) + 1;
additionalRows = new Array(numNewRows);
for (i = 0; i < numNewRows; i++) {
additionalRows[i] = ` <tr>
<td>${lastRowIndex}</td>
<td>
<input type="text" name="name[]"></td>
<td><input type="text" name="other[]"></td>
</tr>`
lastRowIndex = lastRowIndex + 1;
}
$tbody.append(additionalRows.join());
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="insert-rows-amnt" name="insert-rows-amnt" value="<?php echo $tam ?>" />
<button id="add-row" type="button">OK</button>
<table id="one">
<tbody>
<td>
<input type="text" name="id[]" value="No"></td>
<td><input type="text" name="name[]" value="Tommy"> </td>
<td><input type="text" name="other[]" value="Danver"> </td>
</tbody>
</table>
So i have found this will do what i need , it's likely there's gonna be better answer out there. If u have one, please do share. Thank you
$('#add-row').click(function() {
var $tbody, $row, additionalRows;
var numNewRows = parseInt($('#insert-rows-amnt').val(), 10);
if (isNaN(numNewRows) || numNewRows <= 0) {
alert('Please enter number of row');
} else {
$tbody = $('table#one tbody ');
$row = $tbody.find('tr:last');
var lastRowIndex = ($row.index() == -1 ? 0 : $row.index()) + 1;
additionalRows = new Array(numNewRows);
for (i = 0; i < numNewRows; i++) {
additionalRows[i] = ` <tr>
<td>${lastRowIndex}</td>
<td>
<input type="text" name="name[]" class="tommy"></td>
<td><input type="text" name="other[]" class="danver"></td>
</tr>`
lastRowIndex = lastRowIndex + 1;
}
$tbody.append(additionalRows.join());
}
});
$("#add-row").on('click', function() {
var set = $('#tommy,#danver').val();
if (set) {
$('.tommy,.danver ').val(set);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="insert-rows-amnt" name="insert-rows-amnt" value="<?php echo $tam ?>" />
<button id="add-row" type="button">OK</button>
<table id="one">
<tbody>
<td>
<input type="text" name="id[]" value="No"></td>
<td><input type="text" name="name[]" value="Tommy" id="tommy"> </td>
<td><input type="text" name="other[]" value="Danver" id="danver"> </td>
</tbody>
</table>
Here you go with the solution https://jsfiddle.net/r3rbkf72/1/
$('#add-row').click(function() {
var $tbody, $row, additionalRows;
var numNewRows = parseInt($('#insert-rows-amnt').val(), 10);
if (isNaN(numNewRows) || numNewRows <= 0) {
alert('Please enter number of row');
} else {
$tbody = $('table#one tbody ');
$row = $tbody.find('tr:last');
var lastRowIndex = ($row.index() == -1 ? 0 : $row.index()) + 1;
additionalRows = new Array(numNewRows);
var name = $('table#one tbody td:eq(1) input[name="name[]"]').val();
var other = $('table#one tbody td:eq(2) input[name="other[]"]').val();
for (i = 0; i < numNewRows; i++) {
additionalRows[i] = `<tr>
<td>${lastRowIndex}</td>
<td>
<input type="text" name="name[]" value=${name}></td>
<td><input type="text" name="other[]" value=${other}></td>
</tr>`
lastRowIndex = lastRowIndex + 1;
}
$tbody.append(additionalRows.join());
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="insert-rows-amnt" name="insert-rows-amnt" value="<?php echo $tam ?>" />
<button id="add-row" type="button">OK</button>
<table id="one">
<tbody>
<td>
<input type="text" name="id[]" value="No"></td>
<td><input type="text" name="name[]" value="Tommy"> </td>
<td><input type="text" name="other[]" value="Danver"> </td>
</tbody>
</table>
Below two lines of code I have added.
var name = $('table#one tbody td:eq(1) input[name="name[]"]').val();
var other = $('table#one tbody td:eq(2) input[name="other[]"]').val();
This will help you to receive the data from the top row textbox.

reading dynamically added input values into an array php

Every thing is working expect that on adding the dynamic fields,the input added is not captured into the array.Only the values in the only created input are read. HTML PART
<table class="table table-bordered table-hover order-list" >
<thead>
<tr><td>Product</td><td>Price (Ksh.) </td><td>Qty</td><td> (Ksh.)</td></tr>
</thead>
<tbody>
<tr>
<td><input type="text" class="form-control" name="product[]" required="" /></td>
<td><input type="text" class="form-control" name="price[]" required/></td>
<td><input type="text" class="form-control" name="quantity[]" /></td>
<td><input type="text" name="linetotal[]" readonly="readonly" /></td>
<td><a class="deleteRow"> x </a></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5" style="text-align: center;">
<input type="button" id="addrow" value="Add Product" />
</td>
</tr>
<tr>
<td colspan="5">
Grand Total: Ksh.<input type="text" name="grandtotal" readonly="readonly" /><span id="grandtotal"></span>
</td>
</tr>
</tfoot>
</table>
THE javascript to sum up the get the sub total and grand total is as below:
$(document).ready(function () {
var counter = 1;
$("#addrow").on("click", function () {
counter++;
var newRow = $("<tr>");
var cols = "";
cols += '<td><input type="text" name="product' + counter + '"/></td>';
cols += '<td><input type="text" name="price' + counter + '"/></td>';
cols += '<td><input type="text" name="quantity' + counter + '"/></td>';
cols += '<td><input type="text" name="linetotal' + counter + '" readonly="readonly"/></td>';
cols += '<td><a class="deleteRow"> x </a></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
});
$("table.order-list").on("change", 'input[name^="price"], input[name^="quantity"]', function (event) {
calculateRow($(this).closest("tr"));
calculateGrandTotal();
});
$("table.order-list").on("click", "a.deleteRow", function (event) {
$(this).closest("tr").remove();
calculateGrandTotal();
});
});
function calculateRow(row) {
var price = +row.find('input[name^="price"]').val();
var qty = +row.find('input[name^="quantity"]').val();
var linetotal = +row.find('input[name^="linetotal"]').val((price * qty).toFixed(2));
}
function calculateGrandTotal() {
var grandTotal = 0;
$("table.order-list").find('input[name^="linetotal"]').each(function () {
grandTotal += +$(this).val();
});
$("#grandtotal").text(grandTotal.toFixed(2));
}
the php part to read the array is
if(isset($_POST['cinvoice']) && $_SERVER["REQUEST_METHOD"] == "POST" &&is_array($_POST["product"]) && is_array($_POST["quantity"]) && is_array($_POST["price"]) && is_array($_POST["linetotal"]))
{
$recordid="";
$firstname="";
$product="";
$quantity="";
$price="";
$linetotal="";
foreach ($_POST["product"] as $key => $prod) {
$product .= $prod.",";
}
foreach ($_POST["quantity"] as $key => $qty){
$quantity.=$qty. ",";
}
foreach ($_POST["price"] as $key => $prc) {
$price.=$prc. ",";
}
foreach ($_POST["linetotal"] as $key => $linetotal) {
$linetotal.=$linetotal. ",";
}
you should pass textbox name as an array:
cols += '<td><input type="text" name="product[]"/></td>';
cols += '<td><input type="text" name="price[]"/></td>';
cols += '<td><input type="text" name="quantity[]"/></td>';
cols += '<td><input type="text" name="linetotal[]" readonly="readonly"/>
Also you can use implode function in php
foreach ($_POST["product"] as $key => $prod) {
$product .= $prod.",";
}
to
$product = implode(',', $_POST["product"])

javascript function in dynamically input

I'm having an issue using jQuery function multiplication (math) with dynamically created inputs (again created with jQuery). I can't get my function to bind to the new inputs. for the first row its work, but for second row it did not work (second row and more using dynamically input).
Here my html code
<table class="table table-condensed" style="margin-left: 10px;">
<thead>
<tr>
<th width="100px">Nama</th>
<th width="100px">Kode</th>
<th width="100px">Harga</th>
<th width="100px">Jumlah</th>
<th width="100px">Total</th>
<th width="80px"></th>
</tr>
</thead>
<tbody id='itemlist' >
<tr>
<td><input id='nama' name='nama_input[]' class='form-control' /></td>
<td><input id='kode' readonly name='kode_input[]' class='form-control' /></td>
<td><input id='harga' name='harga_input[]' class='form-control' onkeyup="sum();" /></td>
<td><input id='jumlah' autocomplete="off" name='jumlah_input[]' class='form-control' onkeyup="sum();" /></td>
<td><input id='total' name='total_input[]' class='form-control' value=" " /></td>
<td></td>
</tr>
</tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td>
<button type="button" class="btn btn-default" onclick="additem(); return false">
<b>Tambah</b>
</button>
</td>
</tr>
</table>
And this my script
function additem() {
//menentukan target append
var itemlist = document.getElementById('itemlist');
// membuat element
var row = document.createElement('tr');
var nama = document.createElement('td');
var kode = document.createElement('td');
var harga = document.createElement('td');
var jumlah = document.createElement('td');
var total = document.createElement('td');
var aksi = document.createElement('td');
// meng append element
itemlist.appendChild(row);
row.appendChild(nama);
row.appendChild(kode);
row.appendChild(harga);
row.appendChild(jumlah);
row.appendChild(total);
row.appendChild(aksi);
// membuat element input1
var nama_input = document.createElement('input');
nama_input.setAttribute('name', 'nama_input[]');
nama_input.setAttribute('class', 'form-control');
var kode_input = document.createElement('input');
kode_input.setAttribute('name', 'kode_input[]');
kode_input.setAttribute('readonly', '');
kode_input.setAttribute('class', 'form-control');
var harga_input = document.createElement('input');
harga_input.setAttribute('name', 'harga_input[]');
harga_input.setAttribute('class', 'form-control');
harga_input.setAttribute('onkeyup', 'sum();');
var jumlah_input = document.createElement('input');
jumlah_input.setAttribute('name', 'jumlah_input[]');
jumlah_input.setAttribute('class', 'form-control');
jumlah_input.setAttribute('autocomplete', 'off');
jumlah_input.setAttribute('onkeyup', 'sum();');
var total_input = document.createElement('input');
total_input.setAttribute('name', 'total_input[]');
total_input.setAttribute('class', 'form-control');
total_input.setAttribute('readonly', '');
var hapus = document.createElement('span');
// meng append element input
nama.appendChild(nama_input);
kode.appendChild(kode_input);
harga.appendChild(harga_input);
jumlah.appendChild(jumlah_input);
total.appendChild(total_input);
aksi.appendChild(hapus);
hapus.innerHTML = '<button class="btn btn-small btn-default"><b>Hapus</b></button>';
// membuat aksi delete element
hapus.onclick = function () {
row.parentNode.removeChild(row);
};
var namaid = 'nama' + (Math.floor((1 + Math.random()) * 0x10000));
var kodeid = 'kode' + (Math.floor((1 + Math.random()) * 0x10000));
var hargaid = 'harga' + (Math.floor((1 + Math.random()) * 0x10000));
var jumlahid = 'jumlah' + (Math.floor((1 + Math.random()) * 0x10000));
var totalid = 'total' + (Math.floor((1 + Math.random()) * 0x10000));
nama_input.setAttribute('id', namaid);
kode_input.setAttribute('id', kodeid);
harga_input.setAttribute('id', hargaid);
jumlah_input.setAttribute('id', jumlahid);
total_input.setAttribute('id', totalid);
function sum() {
var hrg = document.getElementById('hargaid').value;
var jml = document.getElementById('jumlahid').value;
var result = parseInt(hrg) * parseInt(jml);
if (!isNaN(result)) {
document.getElementById('totalid').value = result;
}
}
$("#" + namaid).autocomplete({
source: "get_barang.php",
minLength: 2,
select: function(event, ui) {
$("#" + kodeid).val(ui.item.kode);
$("#" + hargaid).val(ui.item.harga);
}
});
i++;
}
Any help is appreciated.
You are not passing current id's of inputs to your sum method. and one more thing add jquery onkeyup event to your dynamic inputs. please refer below code -
$(function() {
$('#sample').on('click',additem)
$( "#nama" ).autocomplete({
source: "get_barang.php",
minLength: 2,
select: function( event, ui ) {
$('#kode').val(ui.item.kode);
$('#harga').val(ui.item.harga);
}
});
});
function sum() {
var hrg = document.getElementById('harga').value;
var jml = document.getElementById('jumlah').value;
var result = parseInt(hrg) * parseInt(jml);
if (!isNaN(result)) {
document.getElementById('total').value = result;
}
}
var i = 1;
function additem() {
//menentukan target append
var itemlist = document.getElementById('itemlist');
// membuat element
var row = document.createElement('tr');
var nama = document.createElement('td');
var kode = document.createElement('td');
var harga = document.createElement('td');
var jumlah = document.createElement('td');
var total = document.createElement('td');
var aksi = document.createElement('td');
// meng append element
itemlist.appendChild(row);
row.appendChild(nama);
row.appendChild(kode);
row.appendChild(harga);
row.appendChild(jumlah);
row.appendChild(total);
row.appendChild(aksi);
// membuat element input1
var nama_input = document.createElement('input');
/*nama_input.setAttribute('id', 'nama');*/
nama_input.setAttribute('name', 'nama_input[]');
nama_input.setAttribute('class', 'form-control');
var kode_input = document.createElement('input');
/* kode_input.setAttribute('id', 'kode1');*/
kode_input.setAttribute('name', 'kode_input[]');
kode_input.setAttribute('readonly', '');
kode_input.setAttribute('class', 'form-control');
var harga_input = document.createElement('input');
harga_input.setAttribute('name', 'harga_input[]');
harga_input.setAttribute('class', 'form-control');
//harga_input.setAttribute('onkeyup', 'sum();');
var jumlah_input = document.createElement('input');
jumlah_input.setAttribute('name', 'jumlah_input[]');
jumlah_input.setAttribute('class', 'form-control');
//jumlah_input.setAttribute('onkeyup', 'sum();');
var total_input = document.createElement('input');
total_input.setAttribute('name', 'total_input[]');
total_input.setAttribute('class', 'form-control');
var hapus = document.createElement('span');
// meng append element input
nama.appendChild(nama_input);
kode.appendChild(kode_input);
harga.appendChild(harga_input);
jumlah.appendChild(jumlah_input);
total.appendChild(total_input);
aksi.appendChild(hapus);
hapus.innerHTML = '<button class="btn btn-small btn-default"><b>Hapus</b></button>';
// membuat aksi delete element
hapus.onclick = function () {
row.parentNode.removeChild(row);
};
var namaid = 'nama' + (Math.floor((1 + Math.random()) * 0x10000));
var kodeid = 'kode' + (Math.floor((1 + Math.random()) * 0x10000));
var hargaid = 'harga' + (Math.floor((1 + Math.random()) * 0x10000));
var jumlahid = 'jumlah' + (Math.floor((1 + Math.random()) * 0x10000));
var totalid = 'total' + (Math.floor((1 + Math.random()) * 0x10000));
nama_input.setAttribute('id', namaid);
kode_input.setAttribute('id', kodeid);
harga_input.setAttribute('id', hargaid);
jumlah_input.setAttribute('id', jumlahid);
total_input.setAttribute('id', totalid);
// harga_input.setAttribute("onkeyup", "sum("+hargaid+","+jumlahid+","+totalid+")");
// jumlah_input.setAttribute("onkeyup", "sum("+hargaid+","+jumlahid+","+totalid+")");
$(jumlah_input).on('keyup',function(){
sum(hargaid,jumlahid,totalid)
})
$(harga_input).on('keyup',function(){
sum(hargaid,jumlahid,totalid)
})
function sum(hargaid,jumlahid,totalid) {
var hrg = document.getElementById(hargaid).value;
var jml = document.getElementById(jumlahid).value;
var result = parseInt(hrg) * parseInt(jml);
if (!isNaN(result)) {
document.getElementById(totalid).value = result;
}
}
$("#" + namaid).autocomplete({
source: "get_barang.php",
minLength: 2,
select: function(event, ui) {
$("#" + kodeid).val(ui.item.kode);
$("#" + hargaid).val(ui.item.harga);
}
});
i++;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<table class="table table-condensed" style="margin-left: 10px;">
<thead>
<tr>
<th width="100px">Nama</th>
<th width="100px">Kode</th>
<th width="100px">Harga</th>
<th width="100px">Jumlah</th>
<th width="100px">Total</th>
<th width="80px"></th>
</tr>
</thead>
<tbody id='itemlist' >
<tr>
<td><input id='nama' name='nama_input[]' class='form-control' /></td>
<td><input id='kode' readonly name='kode_input[]' class='form-control' /></td>
<td><input id='harga' name='harga_input[]' class='form-control' onkeyup="sum();" /></td>
<td><input id='jumlah' autocomplete="off" name='jumlah_input[]' class='form-control' onkeyup="sum();" /></td>
<td><input id='total' name='total_input[]' class='form-control' value=" " /></td>
<td></td>
</tr>
</tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td>
<button type="button" id="sample" class="btn btn-default">
<b>Tambah</b>
</button>
</td>
</tr>
</table>
Here is the sample, try this
$(function() {
$(document).on('click', '.btn-remove', function() {
// remove closest row on click of remove button
$(this).closest('tr').remove();
});
$(document).on('input', 'input.harga,input.jumlah', function() {
var hrg = $(this).closest("tr").find('input.harga').val();
var jml = $(this).closest("tr").find('input.jumlah').val();
var result = parseInt(hrg) * parseInt(jml);
if (!isNaN(result)) {
$(this).closest("tr").find('input.total').val(result);
}
})
});
function additem() {
var rowHtml = '<tr>' +
'<td><input name="nama_input[]" class="nama form-control" /></td>' +
'<td><input readonly name="kode_input[]" class="kode form-control" /></td>' +
'<td><input name="harga_input[]" class="harga form-control" /></td>' +
'<td><input autocomplete="off" name="jumlah_input[]" class="jumlah form-control" /></td>' +
'<td><input name="total_input[]" class="total form-control" /></td>' +
'<td><button class="btn btn-small btn-default btn-remove"><b>Hapus</b></button></td>' +
'</tr>';
$('#itemlist').append(rowHtml);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-condensed" style="margin-left: 10px;">
<thead>
<tr>
<th width="100px">Nama</th>
<th width="100px">Kode</th>
<th width="100px">Harga</th>
<th width="100px">Jumlah</th>
<th width="100px">Total</th>
<th width="80px"></th>
</tr>
</thead>
<tbody id='itemlist'>
<tr>
<td>
<input name="nama_input[]" class="nama form-control" />
</td>
<td>
<input readonly name="kode_input[]" class="kode form-control" />
</td>
<td>
<input name="harga_input[]" class="harga form-control" />
</td>
<td>
<input autocomplete="off" name="jumlah_input[]" class="jumlah form-control" />
</td>
<td>
<input name="total_input[]" class="total form-control" />
</td>
<td></td>
</tr>
</tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td>
<button type="button" class="btn btn-default" onclick="additem();
return false">
<b>Tambah</b>
</button>
</td>
</tr>
</table>
I hope It will help

Categories