I have a html table where I add rows dynamically when user clicks on a button. Two cell's number of each row of my table, should be multiplied. I made a function that can multiply 2 cell's number but when I create a new row by pressing add button the function does not work on the new row, it always works on first row on the table.
Here is HTML code:
<div class="table-responsive container">
<table class="table">
<thead class="dark">
<tr>
<th scope="col">SL.</th>
<th scope="col">Item Description</th>
<th scope="col">Price</th>
<th scope="col">Qty.</th>
<th scope="col">Total</th>
<th scope="col">Del</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td><label>
<input type="text" name="name">
</label>
</td>
<td><label>
<input type="text" id="price" oninput="calculate()">
</td>
<td>
<input type="text" id="qt" oninput="calculate()">
</td>
<td>
<input type="text" id="ttl" name='total'>
</td>
<td>
<button class="remove">-</button>
</td>
</tr>
</tbody>
</table>
<button id="addRow">+ Add</button>
</div>
And here is the JavaScript code:
let temp_td = '<tr>' +
'<th scope="row">1</th>' +
'<td><label><input type="text" name="name"></label></td>' +
'<td><label><input type="text" id="price" oninput="calculate()"></td>' +
'<td><input type="text" id="qt" oninput="calculate()"></td>' +
'<td><input type="text" id="ttl" name="total"></td>' +
'<td><button class="remove">-</button></td>' +
'</tr>';
$(function () {
$('tbody').sortable();
$('#addRow').click(function () {
$('tbody').append(temp_td)
});
$(document).on('click', '.remove', function () {
$(this).parents('tr').remove();
});
$('#getValues').click(function () {
const total = [];
let sum = 0;
$('input[name="total"]').each(function (i, elem) {
total.push($(elem).val())
});
for (let i = 0; i < total.length; i++) {
sum += Number(total[i])
}
console.log(total.join(','));
console.log(total);
console.log(sum);
document.getElementById('subtotal').innerHTML = sum;
document.getElementById('total').innerHTML = sum + (sum * 5 / 100);
// document.getElementById('total22').innerHTML = sum;
})
});
function calculate() {
var price = document.getElementById('price').value;
var qt = document.getElementById('qt').value;
var ttl = document.getElementById('ttl');
var multiply = price * qt;
ttl.value = multiply;
}
I tried to change so many things, but it's not working.
You cannot duplicate the IDs in HTML. You can save the row number in a variable which you increment every time you add a new row, and use that variable to generate the IDs:
$(function() {
let row = 1;
$('#addRow').click(function() {
row++;
let temp_td = '<tr><th scope="row">' + row + '</th><td><label><input type="text" name="name"></label></td><td><label><input type="text" id="price' + row + '" oninput="calculate(' + row + ')"></td><td><input type="text" id="qt' + row + '" oninput="calculate(' + row + ')"></td><td><input type="text" id="ttl' + row + '" name="total"></td><td><button class="remove">-</button></td></tr>';
$('tbody').append(temp_td)
});
$(document).on('click', '.remove', function() {
$(this).parents('tr').remove();
});
});
function calculate(r) {
var price = document.getElementById('price' + r).value;
var qt = document.getElementById('qt' + r).value;
var ttl = document.getElementById('ttl' + r);
var multiply = price * qt;
ttl.value = multiply;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div class="table-responsive container">
<table class="table">
<thead class="dark">
<tr>
<th scope="col">SL.</th>
<th scope="col">Item Description</th>
<th scope="col">Price</th>
<th scope="col">Qty.</th>
<th scope="col">Total</th>
<th scope="col">Del</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td><label>
<input type="text" name="name">
</label>
</td>
<td><label>
<input type="text" id="price1" oninput="calculate(1)">
</td>
<td>
<input type="text" id="qt1" oninput="calculate(1)">
</td>
<td>
<input type="text" id="ttl1" name='total'>
</td>
<td>
<button class="remove">-</button>
</td>
</tr>
</tbody>
</table>
<button id="addRow">+ Add</button>
You can also do that to the names if you like. I didn't do that in the code above because it is not essential for this answer.
Alternatively, you can pass the element itself to the calculate() function and then find the other "sibling" elements using jQuery. So you don't need IDs at all.
Related
I have a table in HTML with input fields and I am adding and deleting new rows on button clicks events, What I want every time new fields are created when I type in the price input then the value of each cell with a price is taken, and placed inside the total field.
Because I'm new to the world of JQuery, I'm having trouble getting the theme into the input fields.
// Special increase cells each time by clicking on add
$('#add').click(function() {
var size = $('#table_field tbody').children().length + 1;
var html = '<tr>' + '<td>' + size + '</td>' + '<td><input type="text" class="code" name="code"></td><td><input type="text" class=" form-control totalprice" name="pvu_price[]"></td><td><input type="button" class="btn btn-danger" name="remove" id="remove" value="delete" style="color:white;"></td></tr>';
$('#table_field').append(html);
});
$('#table_field').on('click', '#remove', function() {
$(this).closest('tr').remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered table_field" id="table_field">
<thead>
<tr class="thead-dark">
<th> #</th>
<th style="width: 150px; !important"> code</th>
<th style="width: 150px; !important"> price</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>
<input type="text" class="code" name="code">
<td>
<input type="text" value="" class="sub_code form-control totalprice" id="count" name="pvu_price[]">
</td>
<td>
<input type="button" class="btn btn-success" name="add" id="add" value="add" style="color: white">
</td>
</tr>
</tbody>
<tfoot>
<tr>
</tr>
</tfoot>
</table>
Hello my purpose is when i press the add button to add the second row after adding the first row
saving the first row to the database by going to method and increasing the second row. but when I press the add button, my data goes to the method without taking the values. How can I send the full values?
<form name="productForm" id="productForm"> <div class="table-responsive">
<table class="table table-bordered" id="articles">
<thead>
<tr style="text-align:center">
<th class="text-nowrap" style="text-align:center; vertical-align:middle;">Record No</th>
<th class="text-nowrap" style="text-align:center; vertical-align:middle;">Product Name</th>
<th class="text-nowrap" style="text-align:center; vertical-align:middle;">Product Code</th>
<th class="text-nowrap" style="text-align:center; vertical-align:middle;">Product Price</th>
<th class="text-nowrap" style="text-align:center; vertical-align:middle;">Add</th>
</tr>
</thead>
<tbody>
<tr class="ProductsRecords">
<td><input value=0 min="1" type="number" id="RECORDNO" name="[].RECORDNO" class="form-control name_list" /></td>
<td><input type="text" id="PRODUCTNAME" name="[].PRODUCTNAME" class="form-control name_list" /></td>
<td><input type="number" id="PRODUCTCODE" name="[].PRODUCTCODE" class="form-control name_list" /></td>
<td><input value=0 min="0.0" type="number" id="PRODUCTPRÄ°CE" name="[].PRODUCTPRÄ°CE" class="form-control name_list" /></td>
<td><button type="button" name="add" id="add" class="btn btn-success" onclick="SaveMethod()" >Add</button></td>
</tr>
</tbody>
</table>
</div>
</form>
js.code
var table = document.getElementById("articles");
var array = $(table.rows[table.rows.length-1]).find("input");
for (var j = 0; j < array.length; j++) { array[j].name = array[j].name.replace("[]", "[" + (table.rows.length - 1) + "]");
}
$.ajax({
url: "SavePrice",
method: "POST",
data: $('#productForm').serialize(),
success: function (data) {
}
});
public PRICE SaveMethod(PRICE adding)
{
/// adding properties not set value.
}
Value sample:
Record No:1
Product Name: Pencil
Product Code: Pen
Product Price: 5
I want to this values save db but values is get null.
I'm working on a table which adds rows by add button.
When a new row is added to the table the 'process column' which starts at P0 should be parsed to an integer and 1 should be added to the process of the last row. However this only works for one process after that it displays PNaN. What in the code could be causing this problem? Thanks
<div class="container inline">
<div class="row">
<table class="table" id="configTable">
<thead class="thead-dark">
<tr>
<th scope="col">Process</th>
<th scope="col">Arrival Time</th>
<th scope="col">Burst Time</th>
<th scope="col">Quantum</th>
<th scope="col">Priority</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">P0</th>
<td>0</td>
<td><input autofocus class="burstTime" type="number" min="1" max="15"></td>
<td><input class="quantumTime" type="number" min="1" max="10"></td>
<td><input class="priorityTime" type="number" min="1" max="10"></td>
</tr>
</tbody>
</table>
<input type="button" value="+" onclick="addRow();">
<input id="del" type="button" value="-" onclick="deleteRow();">
</div>
</div>
//ADD NEW ROW
function addRow() {
var lastRow = $('table tr:last');
var lastProcessNumber = parseInt(lastRow.children()[0].innerText);
var newRow = '<tr><th>P'
+ (lastProcessNumber + 1)
+ '</td><td><input class="arrivalTime" type="number"/>'
+ '</td><td><input class="burstTime" type="number"/></td>'
+ '</td><td><input class="quantumTime" type="number"/></td>'
+ '</td><td><input class="priorityTime" type="number"/></td>'
lastRow.after(newRow);
parseInt()
If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. parseInt truncates numbers to integer values. Leading and trailing spaces are allowed.
Replace the character P with empty string:
var lastProcessNumber = parseInt(lastRow.children()[0].innerText.replace('P',''));
//ADD NEW ROW
function addRow() {
var lastRow = $('table tr:last');
var lastProcessNumber = parseInt(lastRow.children()[0].innerText.replace('P',''));
var newRow = '<tr><th>P'
+ (lastProcessNumber + 1)
+ '</td><td><input class="arrivalTime" type="number"/>'
+ '</td><td><input class="burstTime" type="number"/></td>'
+ '</td><td><input class="quantumTime" type="number"/></td>'
+ '</td><td><input class="priorityTime" type="number"/></td>'
lastRow.after(newRow)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container inline">
<div class="row">
<table class="table" id="configTable">
<thead class="thead-dark">
<tr>
<th scope="col">Process</th>
<th scope="col">Arrival Time</th>
<th scope="col">Burst Time</th>
<th scope="col">Quantum</th>
<th scope="col">Priority</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">P0</th>
<td>0</td>
<td><input autofocus class="burstTime" type="number" min="1" max="15"></td>
<td><input class="quantumTime" type="number" min="1" max="10"></td>
<td><input class="priorityTime" type="number" min="1" max="10"></td>
</tr>
</tbody>
</table>
<input type="button" value="+" onclick="addRow();">
<input id="del" type="button" value="-" onclick="deleteRow();">
</div>
</div>
There is a P in the innerText and it's preventing parseInt() from parsing correctly.
Replace anything in your text that not a number with the empty string so parseInt() works.
This
var lastProcessNumber = parseInt(lastRow.children()[0].innerText);
becomes
var lastProcessNumber = parseInt(lastRow.children()[0].innerText.replace(/[^\d]/,''));
https://jsbin.com/vizazinewe/edit?html,js,console,output
Working fiddle: https://jsbin.com/zizayoyufu/2/edit?js,console,output
Your JS adjusted to work:
//ADD NEW ROW
function addRow() {
var lastRow = $('table tr:last');
const processField = lastRow.children()[0].innerText;
const processIdRegex = new RegExp("\\d+");
let processId = 0;
if(processIdRegex.test(processField)) {
processId = parseInt(processField.match(processIdRegex)[0]);
}
var lastProcessNumber = processId;
var newRow = '<tr><th>P'
+ (lastProcessNumber + 1)
+ '</td><td><input class="arrivalTime" type="number"/>'
+ '</td><td><input class="burstTime" type="number"/></td>'
+ '</td><td><input class="quantumTime" type="number"/></td>'
+ '</td><td><input class="priorityTime" type="number"/></td>'
lastRow.after(newRow);
}
parseInt returns NaN if the first character encoutered is string.
I created a table where I can dynamically add multiple rows to it. There's a column to add cost. Now I want to
get total cost value of each row at the bottom of the table. How can I get this using JavaScript?
Here is my html code for dynamic table.
<table>
<thead>
<tr>
<th>No</th>
<th>Title</th>
<th cost</th>
</tr>
</thead>
<tbody id="body">
<tr>
<th>1</th>
<td>
<input type="text" id="title" name="title[]" />
</td>
<td>
<input type="text" id="cost" name="cost[]" />
</td>
</tr>
</tbody>
</table>
Javascript function:
$(function(){
$('.addrow').click(function(){
addrow();
});
function addrow()
{
var row =($('#body tr').length-0)+1;
var tr ='<tr>'+
'<th>'+row+'</th>'+
'<td><input type="text" id="title" name="title[]" ></td>'+
'<td><input type="text" id="cost" name="cost[]" /></td>'+
'</tr>';
$('#body').append(tr);
}
});
You should iterate the input tags that belong to the table and have an id starting with "cost".
Also, you can not add the row directly to the body, you want to add it after the last row already created.
Try out this (edit:) fiddle (old habits die hard) snippet .
$(document).ready(function(){
$('#addRow').click(function(){
addRow();
});
$('#totalRow').click(function(){
totalRow();
});
function addRow()
{
var rowId = $('#myTable tr').length;
$('#myTable > tbody:last-child').append(
'<tr><th>' + rowId + ' </th>' +
'<td><input type="text" id="title' + rowId + '" /></td>' +
'<td><input type="text" id="cost' + rowId + '"</td></tr>'
);
}
function totalRow()
{
var rowId = $('#myTable tr').length;
var val = 0;
$("#myTable [id^=cost]").each(function() {
val += parseFloat($(this).val());
});
$('#myTable > tbody:last-child').append(
'<tr><th>T</th>' +
'<td><input type="text" id="totalRow" value="TOTAL" /></td>' +
'<td><input type="text" id="totalCost" value="' + val +'" /></td></tr>'
);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="addRow">Add row</div>
<div id="totalRow">Calculate total row</div>
<br>
<table id="myTable">
<thead>
<tr>
<th>No</th>
<th>Title</th>
<th>Cost</th>
</tr>
</thead>
<tbody>
<tr>
<th>1</th>
<td>
<input type="text" id="title1" value="Example" />
</td>
<td>
<input type="text" id="cost1" value="25" />
</td>
</tr>
</tbody>
</table>
Hope it helps!
If text inputs are the only inputs used, try using https://api.jquery.com/input-selector/ to get all the input selectors.
You can iterate through the input selectors, aggregate the values to give you the total.
NOTE: As mentioned in the comments, do not use same id for all the input tags. It is not a best practice
I create rows dynamically using the event onfocus of d or w field. I got that correct,but the radio button- when i choose dm, d should be disabled and cm, w should be disabled. I am not sure how to do that. Please help me out
<table class="table table-bordered table-hover" id="tvtable">
<thead>
<tr>
<th width="10%" style="text-align: center;">Type</th>
<th width="20%" style="text-align: center;">A</th>
<th width="20%" style="text-align: center;">d</th>
<th width="20%" style="text-align: center;">w</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="radio" name="wd0" id="rd" value="dr" />Dm
<br/>
<input type="radio" name="wd0" id="rc" value="cr" />Cm</td>
<td>
<select id="m0" class="form-control"></select>
</td>
<td>
<input class="form-control c1 amt" type="number" id="w0" name="amt1" />
</td>
<td>
<input class="form-control c2 amt" type="number" id="d0" name="amt2" />
</td>
</tr>
</tbody>
</table>
$(document).ready(function ()
{
if ($('#rd').prop('checked'))
{
$(".c1").attr("disabled", "disabled");
}
else if($('#rc').prop('checked'))
{
$(".c2").attr("disabled", "disabled");
}
var counter = 0;
$(document).on("focus", ".amt", function (event)
{
counter++;
var list = '<tr><td><input type="radio" name="wd' + counter + '" id="rd" value="dr" />Dm<br/><input type="radio" name="wd' + counter + '" id="rc" value="cr" />Cm</td><td><select id="m' + counter +
'" class="form-control "></select></td><td><input class="form-control c1 amt" type="number" id="w' + counter + '" name="amount" /></td><td><input class="form-control c2 amt" type="number" id="d' + counter + '" name="amount" /></td></tr>';
$('#tvtable').append(list);
});
});
http://jsfiddle.net/A8G5v/
You did not include jQuery in JSfiddle plus syntax errors.
You are appending checkboxes dynamically, so the if()..else() won't work on document.ready.
Add a delegated change event.
$(document).on('change', ':radio', function () {
if ($(this).prop('checked') && $(this).val() == 'dr') {
$(this).parents('tr').find(".c1").attr("disabled", "disabled");
$(this).parents('tr').find(".c2").removeAttr("disabled");
} else{
$(this).parents('tr').find(".c2").attr("disabled", "disabled");
$(this).parents('tr').find(".c1").removeAttr("disabled");
}
});
Note : Your code is generating duplicate IDs which wont work for later append.
Updated Demo