how to apply same id and function to multiple rows in javascipt - javascript

I write code of html and javascript in which when i click on button it add a new row.It is working fine now i have to find total by multiplying quantity and cost.It works for first row but if i add more rows it not work
<table class="table table-bordered table-striped">
<thead>
<th>#</th>
<th>Item Name</th>
<th>Batch No</th>
<th>Remarks</th>
<th>Quantity</th>
<th>Cost Per Piece</th>
<th>Total</th>
<th>Action</th>
</thead>
<tbody id="tbody">
</tbody>
<center><button type="button" name="" onclick="additem()" class="btn btn-success"> Add</button></center></td>
and javascript code is
function additem() {
x++;
var html="<tr";
html += "<td><center>"+x+"</center></td>";
html += "<td><input type='text' class='form-control' name='product_name'></td>";
html += "<td><input type='text' class='form-control' name='batch_no'></td>";
html += "<td><input type='text' class='form-control' name='remarks'></td>";
html += "<td><input type='number' class='form-control' oninput='calculate()' id='qty' name='total_qty'></td>";
html += "<td><input type='number' class='form-control' oninput='calculate()' id='cost' name='cost'></td>";
html += "<td><input type='number' class='form-control' id='total' name='total' readonly></td>";
html += "<td><button type='button' id='btn' class='btn btn-danger'><i class='fa fa-remove'></i></button></td>";
html += "</tr>";
document.getElementById("tbody").insertRow().innerHTML= html;
}

You can set a dynamic id on these inputs using x variable:
Check out this jsfiddle link
let x = 0;
function additem() {
x++;
var html=`<tr;
<td><center>${x}</center></td>
<td><input type='text' class='form-control' name='product_name'></td>
<td><input type='text' class='form-control' name='batch_no'></td>
<td><input type='text' class='form-control' name='remarks'></td>
<td><input id='qty${x}' type='number' class='form-control' oninput='calculate(${x})' id='qty' name='total_qty'></td>
<td><input id='cost${x}' type='number' class='form-control' oninput='calculate(${x})' id='cost' name='cost'></td>
<td><input type='number' class='form-control' id='total${x}' name='total' readonly></td>
<td><button type='button' id='btn' class='btn btn-danger'><i class='fa fa-remove'></i></button></td>
</tr>`;
document.getElementById("tbody").insertRow().innerHTML= html;
}
function calculate(x) {
const qty = document.getElementById(`qty${x}`).value;
const cost = document.getElementById(`cost${x}`).value;
const totalElem = document.getElementById(`total${x}`);
totalElem.value = qty * cost
}

You need to create a unique id for each row and get the element by unique Id. Something like this.
let x = 0;
function additem() {
x++;
var html = "<tr";
html += "<td><center>" + x + "</center></td>";
html += "<td><input type='text' class='form-control' name='product_name'></td>";
html += "<td><input type='text' class='form-control' name='batch_no'></td>";
html += "<td><input type='text' class='form-control' name='remarks'></td>";
html += "<td><input id='qty_" + x + "' type='number' class='form-control' oninput='calculate(" + x + ")' id='qty' name='total_qty'></td>";
html += "<td><input id='cost_" + x + "' type='number' class='form-control' oninput='calculate(" + x + ")' id='cost' name='cost'></td>";
html += "<td><input id='total_" + x + "' type='number' class='form-control' id='total' name='total' readonly></td>";
html += "<td><button type='button' id='btn' class='btn btn-danger'><i class='fa fa-remove'></i></button></td>";
html += "</tr>";
document.getElementById("tbody").insertRow().innerHTML = html;
}
function calculate(x) {
let qty;
let cost
if (document.getElementById('qty_' + x))
qty = document.getElementById('qty_' + x).value;
if (document.getElementById('cost_' + x))
cost = document.getElementById('cost_' + x).value;
let total = qty * cost;
if (document.getElementById('total_' + x))
document.getElementById('total_' + x).value = total;
}

Related

How to set Javascript's variable value inside <input value=''">

I do not know how to formulate this question but it is near close to my issue. I am trying to make a Point of sale system so when client clicks in each product it adds in the table. There are no issues in my code but I do not know how to set the product's price using a textbox when using .append.
This is my code:
$(".agregarListaF").click(function (e) {
e.preventDefault();
var padre = $(this);
var hijos = padre.children().children("span");
var i = 0;
var datos = new Array();
hijos.each(function () {
switch (i) {
case 0:
datos[0] = $(this).text();
break;
case 1:
padre;
datos[1] = $(this).text();
break;
case 2:
padre;
datos[2] = $(this).text();
break;
}
i++;
});
console.log(datos[0]);
console.log(datos[1]);
$(".detallefactura").append(
"<tr>" +
"<td>" +
datos[0] +
"</td>" +
"<td>" +
datos[1] +
"</td>" +
"<td>" +
"<input type='text' class='form-control text-center' value='1'>" +
"</td>" +
"<td>" +
"<input type='text' class='form-control text-center' value=''>" +
"</td>" +
"<td class='tota-sub-fila'>" +
parseFloat(Math.floor(datos[2]) * parseFloat(1)).toFixed(2) +
"</td>"
);
});
My issue is in the line:
+ "<td>" + "<input type='text' class='form-control text-center' value=''>" + "</td>"
I want to add javascript value variable inside * input value=''* but I know It wont work but I tried it:
+ "<td>" + "<input type='text' class='form-control text-center' value='datos[2]'>" + "</td>"
This is my point of sale view:
In the column precio is where I want to set the price inside that textbox.
How do I solve this?
Please try this code,To How to set Javascript's variable value inside
<!DOCTYPE html>
<html>
<head>
<title>
JavaScript| Set the value of an input field.
</title>
</head>
<body style="text-align:center;" id="body">
<input type='text' id='id1' />
<br>
<br>
<button onclick="gfg_Run()">
click to set
</button>
<p id="GFG_DOWN" style="color:green; font-size: 20px;font-weight: bold;"></p>
<script>
var el_down = document.getElementById("GFG_DOWN");
var inputF = document.getElementById("id1");
function gfg_Run() {
inputF.setAttribute('value', 'defaultValue');
el_down.innerHTML = "Value = " + "'" + inputF.value + "'";
}
</script>
</body>
</html>
I hope this information will be useful.
Thank you.
Follow this using template literals
const html = `<tr>
<td>${datos[0]}</td>
<td>${datos[1]}</td>
<td><input type="text" class="form-control text-center" value="${datos[3]}"></td>
<td><input type="text" class="form-control text-center" value="${datos[4]}"</td>
<td class="tota-sub-fila">${parseFloat((Math.floor(datos[2])) * parseFloat(1)).toFixed(2)}</td>
</tr>`;
$(.detallefactura").append(html);
You can do:
var variable="x";
"<input type='text' class='form-control text-center' value='"+ variable +"'>";
Or,
`<input type='text' class='form-control text-center' value='${variable}'>`
you can use Template literals like this instead of having this concatenation:
$(.detallefactura").append(`<tr>
<td> ${datos[0]} </td>
<td> ${datos[1]} </td>
<td> <input type='text' class='form-control text-center' value='1'> </td>
<td> <input type='text' class='form-control text-center' value='${datos[2]}'> </td>
<td class='tota-sub-fila'> ${parseFloat((Math.floor(datos[2])) * parseFloat(1)).toFixed(2)} </td>
`);

how to get a particular cell from a dynamically added row based on its id in jQuery

I have a table with the id line-creation-table which grows or shrinks dynamically. Each row in this table looks like this:
<tr>
<td><input type="text" name="brand" /></td>
<td><input type="text" name="itemRefNo" id="itemRefNo"/></td>
<td> <input type="number" name="quantity" value="1"/></td>
<td> <input type="text" name="unitPrice" /></td>
<td><input type="date" name="deliveryDate" /></td>
<td><input type="button" value="Show Previous Actions" id="showPreviousActions"/></td>
</tr>
these rows are added dynamically. Now when the showPreviousActions button is clicked I want to retrieve the value from itemRefNo cell from the row where the button is clicked.
I tried this:
$("#line-creation-table").on('click', 'input[id="showPreviousActions"]', function(event) {
var itemRefNo = $(this).parent().find('input[id="itemRefNo"]').val();
}
and this:
var itemRefNo = $(event.target).closest('input[id="itemRefNo"]').val();
but neither worked. When I console log the itemRefNo variable I get undefined. How can I solve it? Thank you very much.
This code:
$(this).parent()
takes the current item (this = the button) and gets its parent, which is the td of the button, so attempting to then find an input in an adjacent cell fails.
A quick fix would be to get the tds parent, the tr, giving:
$("#line-creation-table").on('click', 'input[id="showPreviousActions"]', function(event) {
var itemRefNo = $(this).parent().parent()
.find('input[id="itemRefNo"]').val();
}
better would be to use closest() to find the button's row:
$("#line-creation-table").on('click', 'input[id="showPreviousActions"]', function(event) {
var row = $(this).closest("tr");
var itemRefNo = row.find('input[id="itemRefNo"]').val();
}
Where closest() is the same as calling .parent() recursively until it finds a matching node (ie, closest parent).
you can use
$('#showPreviousActions').click(function () {
var aa = $(this).closest('tr').find('#itemRefNo').val();
});
Ok, a very stupid mistake on my side. When creating a row for this table dynamically, I forgot to change the code there so that in the newly created rows there would be an input with the id itemRefNo. The old code:
$('#line-creation-table').append("<tr>" +
"<td><input type='text' name='brand' /></td>" +
"<td><input type='text' name='itemRefNo' /></td>" +
"<td> <input type='number' name='quantity' value='1'/></td>" +
"<td> <input type='text' name='unitPrice' /></td>" +
"<td><input type='date' name='deliveryDate' /></td>" +
"<td><input type='button' value='Show Previous Actions' id='showPreviousActions'/></td>" +
"<td><input type='button' value='Delete' id='deleteRowButton' /></td>" +
"</tr>")
new code:
$('#line-creation-table').append("<tr>" +
"<td><input type='text' name='brand' /></td>" +
"<td><input type='text' name='itemRefNo' id='itemRefNo'/></td>" +
"<td> <input type='number' name='quantity' value='1'/></td>" +
"<td> <input type='text' name='unitPrice' /></td>" +
"<td><input type='date' name='deliveryDate' /></td>" +
"<td><input type='button' value='Show Previous Actions' id='showPreviousActions'/></td>" +
"<td><input type='button' value='Delete' id='deleteRowButton' /></td>" +
"</tr>")
So both of #freedomn-m 's suggestions work.

Add a blank row in HTML Table

I have an HTML table that adds a new row below where the button in current row is located. Currently when the row is created it generates a clone of the row above including the data. I would like this to be a row that has no entry for the input values rather than a clone of the values above.
Javascript
function addRow(row)
{
var i = row.parentNode.parentNode.rowIndex;
var tr = document.getElementById('Table').insertRow(i+1);
tr.innerHTML = row.parentNode.parentNode.innerHTML;
tr.children[0].innerHTML = tr.parentNode.querySelectorALL("tr").length-1;
}
<table id="Table" border="1">
<tr>
<td><b>Measured Depth</b></td>
<td><b>Inclination</b></td>
<td><b>Azimuth</b></td>
<td><b>Delete?</b></td>
<td><b>Add Row?</b></td>
</tr>
<tr>
<td><input size=25 type="text" id="Measured Depth0[]" contenteditable="true" value='339'></td>
<td><input size=25 type="text" id="Inclination0[]" contenteditable='true' value='0.540000021'></td>
<td><input size=25 type="text" id="Azimuth0[]" contenteditable='true' value='310.7200012'></td>
<td><input type="button" id="delbutton0" value="Delete" onclick="deleteRow(this)"/></td>
<td><input type="button" id="addmorebutton0" value="Add Row Below" onclick="addRow(this)"/></td>
</tr>
</table>
after you add a row, you can just set the values of all inputs in that row to "". get all the inputs of type text using tr.querySelectorAll("input[type='text']") and using a loop set values of all to ""
function addRow(row)
{
var i = row.parentNode.parentNode.rowIndex;
var tr = document.getElementById('Table').insertRow(i+1);
tr.innerHTML = row.parentNode.parentNode.innerHTML;
var inputs = tr.querySelectorAll("input[type='text']");
for(var i=0; i<inputs.length; i++)
inputs[i].value = "";
}
<table id="Table" border="1">
<tr>
<td><b>Measured Depth</b></td>
<td><b>Inclination</b></td>
<td><b>Azimuth</b></td>
<td><b>Delete?</b></td>
<td><b>Add Row?</b></td>
</tr>
<tr>
<td><input size=25 type="text" id="Measured Depth0[]" contenteditable="true" value='339'></td>
<td><input size=25 type="text" id="Inclination0[]" contenteditable='true' value='0.540000021'></td>
<td><input size=25 type="text" id="Azimuth0[]" contenteditable='true' value='310.7200012'></td>
<td><input type="button" id="delbutton0" value="Delete" onclick="deleteRow(this)"/></td>
<td><input type="button" id="addmorebutton0" value="Add Row Below" onclick="addRow(this)"/></td>
</tr>
</table>
You can do this very easily with jQuery:
var $lastRow = $("table#Table tr:last-child");
var $newRow = $lastRow.clone()
$newRow.find("input[type=text]").val(''); //empty all the values in text inputs
$("table#Table").append( $newRow );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="Table" border="1">
<tr>
<td><b>Measured Depth</b></td>
<td><b>Inclination</b></td>
<td><b>Azimuth</b></td>
<td><b>Delete?</b></td>
<td><b>Add Row?</b></td>
</tr>
<tr>
<td><input size=25 type="text" id="Measured Depth0[]" contenteditable="true" value='339'></td>
<td><input size=25 type="text" id="Inclination0[]" contenteditable='true' value='0.540000021'></td>
<td><input size=25 type="text" id="Azimuth0[]" contenteditable='true' value='310.7200012'></td>
<td><input type="button" id="delbutton0" value="Delete" onclick="deleteRow(this)"/></td>
<td><input type="button" id="addmorebutton0" value="Add Row Below" onclick="addRow(this)"/></td>
</tr>
</table>
Add this line of code to your function to empty values in HTML code:
function addRow(row)
{
var i = row.parentNode.parentNode.rowIndex;
var tr = document.getElementById('Table').insertRow(i+1);
tr.innerHTML = row.parentNode.parentNode.innerHTML;
tr.innerHTML = tr.innerHTML.replace(/value='.*'/, "value=''"); //this will remove all values from your html
tr.children[0].innerHTML = tr.parentNode.querySelectorALL("tr").length-1;
}
Using JQuery:
function addRow(){
var t = $("#Table tr").last().clone();
t.find("input").each(function(i,element) {
$(element).val("");
});
t.appendTo("#Table");
}
I can suggest you do this - define table rows in javascript and add those directly. Also, use th for table headers
function edit_row(no) {
document.getElementById("edit_button" + no).style.display = "none";
document.getElementById("save_button" + no).style.display = "block";
// get elements
var measured = document.getElementById("measured_row" + no);
var inclination = document.getElementById("inclination_row" + no);
var azimuth = document.getElementById("azimuth_row" + no);
// get their values
var measured_data = measured.innerHTML;
var inclination_data = inclination.innerHTML;
var azimuth_data = azimuth.innerHTML;
// replace by editable input tags
measured.innerHTML = "<input type='text' id='measured_text" + no + "' value='" + measured_data + "'>";
inclination.innerHTML = "<input type='text' id='inclination_text" + no + "' value='" + inclination_data + "'>";
azimuth.innerHTML = "<input type='text' id='azimuth_text" + no + "' value='" + azimuth_data + "'>";
}
function save_row(no) {
// same as in edit function
var measured_val = document.getElementById("measured_text" + no).value;
var inclination_val = document.getElementById("inclination_text" + no).value;
var azimuth_val = document.getElementById("azimuth_text" + no).value;
document.getElementById("measured_row" + no).innerHTML = measured_val;
document.getElementById("inclination_row" + no).innerHTML = inclination_val;
document.getElementById("azimuth_row" + no).innerHTML = azimuth_val;
document.getElementById("edit_button" + no).style.display = "block";
document.getElementById("save_button" + no).style.display = "none";
}
function delete_row(no) {
document.getElementById("row" + no + "").outerHTML = "";
}
function add_row() {
var new_measured = document.getElementById("new_measured").value;
var new_inclination = document.getElementById("new_inclination").value;
var new_azimuth = document.getElementById("new_azimuth").value;
var table = document.getElementById("data_table");
var table_len = (table.rows.length) - 1;
var row = table.insertRow(table_len).outerHTML = "<tr id='row" + table_len + "'><td id='measured_row" + table_len + "'>" + new_measured + "</td><td id='inclination_row" + table_len + "'>" + new_inclination + "</td><td id='azimuth_row" + table_len + "'>" + new_azimuth + "</td><td><input type='button' id='edit_button" + table_len + "' value='Edit' class='edit' onclick='edit_row(" + table_len + ")'> <input type='button' id='save_button" + table_len + "' value='Save' class='save' onclick='save_row(" + table_len + ")'> <input type='button' value='Delete' class='delete' onclick='delete_row(" + table_len + ")'></td></tr>";
document.getElementById("new_measured").value = "";
document.getElementById("new_inclination").value = "";
document.getElementById("new_azimuth").value = "";
}
<table align='center' cellspacing=2 cellpadding=5 id="data_table" border=1>
<tr>
<th>Measured Depth</th>
<th>Inclination</th>
<th>Azimuth</th>
</tr>
<tr id="row1">
<td id="measured_row1">339</td>
<td id="inclination_row1">0.540000021</td>
<td id="azimuth_row1">310.7200012</td>
<td>
<input type="button" id="edit_button1" value="Edit" class="edit" onclick="edit_row('1')">
<input type="button" id="save_button1" value="Save" class="save" onclick="save_row('1')">
<input type="button" value="Delete" class="delete" onclick="delete_row('1')">
</td>
</tr>
<tr>
<td><input type="text" id="new_measured"></td>
<td><input type="text" id="new_inclination"></td>
<td><input type="text" id="new_azimuth"></td>
<td><input type="button" class="add" onclick="add_row();" value="Add Row"></td>
</tr>
</table>

Dynamic Copy Contents from Textboxes

This is my full code. Dynamic rows are generating on add button and deleting on delete icon image. i want to copy the contents of 2 columns from it.
This is my full code. Dynamic rows are generating on add button and deleting on delete icon image. i want to copy the contents of 2 columns from it.
JavaScript Code:
<script type="text/javascript">
var cc = 1;
function addTableRow(jQtable){
var id=cc;
jQtable.each(function() {
var data = "<tr><td class='Arial_4C8966' align='center'><input name='InvoiceDate[]' type='date' class='form-control' placeholder='' style='width:160px' id='InvoiceDate_" + cc + "' size='10' onclick='showData(this.value," + cc + ")'/></td><td class='Arial_4C8966'><input name='Details[]' type='text' class='form-control' style='width:240px' id='Details_" + cc + "' size='10'/></td><td class='Arial_4C8966'><input name='ReceiptNo[]' type='text' class='form-control' style='width:180px' id='ReceiptNo_" + cc + "' size='10' /></td><td class='Arial_4C8966'><input name='Amount[]' class='form-control' style='width:180px' type='text' onblur='copy_data(this);' id='Amount_" + cc + "' size='10' /></td><td class='Arial_4C8966'><input name='Total[]' style='width:180px' class='form-control' type='text' id='Total_" + cc + "' size='10' /></td><td class='Arial_4C8966'><img src='assets/img/pictures.png' style='cursor:pointer; border:0px; width:16px;' onclick='setDeletedID("+ cc +");$(this).parent().parent().remove();' />
var $table = $(this);
var n = $('tr:last td', this).length;
var tds = data;
cc++;
if ($('tbody', this).length > 0) {
$('tbody', this).append(tds);
} else {
$(this).append(tds);
}
});
}
function setDeletedID(itemID){
objReceiptNo=document.getElementById('ReceiptNo_'+itemID)
if(objReceiptNo.value!=''){
if(document.getElementById('txtDeletedIDs').value==''){
document.getElementById('txtDeletedIDs').value= objReceiptNo.value;
}else{
document.getElementById('txtDeletedIDs').value+= ', '+objReceiptNo.value;
}
}
}
</script>
HTML CODE:
<div class="row clearfix">
<div class="col-md-12 column">
<table class="table table-bordered table-hover" id="dynamicInput">
<tr class="Form_Text_Label">
<td align="center">INVOICE DATE*</td>
<td align="center">DETAILS*</td>
<td align="center">RECEIPT NO*</td>
<td align="center">AMOUNT*</td>
<td align="center">TOTAL*</td>
<td align="center"></td>
</tr>
</table>
</div>
</div>
<div class="col-sm-6">
<input type="button" value="Add" class="frmBtns" onclick="addTableRow($('#dynamicInput'));"
onblur="copy_data(this);" style="font-family: Calibri; font-size: 15px;">
<br>
</div>
Please take a look at revised HTML and JS code. Hope it will work for you:
var cc = 1;
CalculateGrandTotal();
function addTableRow(jQtable){
var id=cc;
jQtable.each(function() {
var data = "<tr><td class='Arial_4C8966' align='center'><input name='InvoiceDate[]' type='date' class='form-control' placeholder='' style='width:160px' id='InvoiceDate_" + cc + "' size='10' onclick='showData(this.value," + cc + ")'/></td><td class='Arial_4C8966'><input name='Details[]' type='text' class='form-control' style='width:240px' id='Details_" + cc + "' size='10'/></td><td class='Arial_4C8966'><input name='ReceiptNo[]' type='text' class='form-control' style='width:180px' id='ReceiptNo_" + cc + "' size='10' /></td><td class='Arial_4C8966'><input name='Amount[]' class='form-control' style='width:180px' type='text' onblur='copy_data(this);' id='Amount_" + cc + "' size='10' /></td><td class='Arial_4C8966'><input name='Total[]' style='width:180px' class='form-control Total' type='text' id='Total_" + cc + "' size='10' /></td><td class='Arial_4C8966'><img src='assets/img/pictures.png' style='cursor:pointer; border:0px; width:16px;' onclick='setDeletedID("+ cc +");$(this).parent().parent().remove();' />";
var $table = $(this);
var n = $('tr:last td', this).length;
var tds = data;
cc++;
if ($('tbody', this).length > 0) {
$('tbody', this).append(tds);
} else {
$(this).append(tds);
}
});
}
function copy_data(obj){
var current = $(obj);
var currentTr = current.closest("tr");
var currentTotalElem = currentTr.find(".Total");
currentTotalElem.val(current.val());
CalculateGrandTotal();
}
//calculate the grand total
function CalculateGrandTotal(){
var grandTotal = 0;
$(".Total").each(function(){
var currVal = $(this).val();
if(!isNaN(currVal))
{
grandTotal += parseFloat(currVal);
}
});
$("#grand_total").val(grandTotal);
}
function setDeletedID(itemID){
objReceiptNo=document.getElementById('ReceiptNo_'+itemID)
if(objReceiptNo.value!=''){
if(document.getElementById('txtDeletedIDs').value==''){
document.getElementById('txtDeletedIDs').value= objReceiptNo.value;
}else{
document.getElementById('txtDeletedIDs').value+= ', '+objReceiptNo.value;
}
}
}
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<div class="row clearfix">
<div class="col-md-12 column">
<table class="table table-bordered table-hover" id="dynamicInput">
<tr class="Form_Text_Label">
<td align="center">INVOICE DATE*</td>
<td align="center">DETAILS*</td>
<td align="center">RECEIPT NO*</td>
<td align="center">AMOUNT*</td>
<td align="center">TOTAL*</td>
<td align="center"></td>
</tr>
</table>
</div>
</div>
<div class="col-sm-6">
<input type="button" value="Add" class="frmBtns" onclick="addTableRow($('#dynamicInput'));"
style="font-family: Calibri; font-size: 15px;"></input>
<br>
<label class="col-sm-3 text-right ">Grand Total :</label> <div class="col-sm-3"> <td class="Arial_4C8966"><input name="grand_total" type="text" class="form-control" id="grand_total" size="10" />
</div>
Please try to use above JS and HTML code as it is. Replace your corresponding code with above one. Please note: your function setDeletedID doesn't work as provided HTML don't contain any element with an id txtDeletedIDs. Please check that again. Thanks.

JQuery - can't delete table row

I don't know what is an error in this code. I have correctly detect parent. But doesn't work.
This is HTML code
<table>
<tbody class="tbody">
<tr id="row_1">
<td>
<input type="text" id="row_1_jumlah_1" name="row_1_jumlah_1" value="1" readonly="readonly" class="form-control" />
</td>
<td></td>
</tr>
<input type="button" class="btn green" value="Tambah Satuan" id="add_row" style="margin-bottom: 10px; margin-left:10px;" />
</tbody>
</table>
This is js code
$("#add_row").click(function () {
var last_index_tr = $(".tbody tr").length;
var new_index_tr = $(".tbody tr").length + 1;
var row = $("<tr id='row_" + new_index_tr + "'>");
var input = $("<td> <input class='form-control' type='text' id='row_" + new_index_tr + "_jumlah_1' name='row_" + new_index_tr + "_jumlah_1' value='1' readonly='readonly' /> </td>");
var action_delete = $("<td> <input class='btn btn-danger' type='button' id='row_" + new_index_tr + "_delete' class='delete' value='delete' /> </td>");
action_delete.click(function () {
var parent_1 = action_delete.parent();
var get_tr_parent_id = $(parent_1).attr('id');
//document.write(get_tr_parent_id);
$("#".get_tr_parent_id).remove();
});
row.append(input);
row.append(action_delete);
row.append("</tr>");
$(".tbody").append(row);
});
I want to remove tr inside table with delete button or action_delete(see js code). I have get parent perfectly. But I can't still delete tr.
Try this, You can use .on to hook the click handler for that delete button which is being created at runtime. Though your hooking is working, Using .on is a good practice while dealing with elements which are created dynamically. And by the way you have to concatenate the # with + Not with . That was the problem with your code, See your code working over here.
var action_delete = $("<td> <input class='btn btn-danger' type='button' id='row_" + new_index_tr +"_delete' class='delete' value='delete' /> </td>");
$(document).on('click',"#row_" + new_index_tr +"_delete",function(){
$(this).closest('tr').remove();
});
DEMO
Edit:
Try the following code, This will register to the click event commonly only once for your entire delete buttons.
$("#add_row").click(function () {
var last_index_tr = $(".tbody tr").length;
var new_index_tr = $(".tbody tr").length + 1;
var row = $("<tr id='row_" + new_index_tr + "'>");
var input = $("<td> <input class='form-control' type='text' id='row_" + new_index_tr + "_jumlah_1' name='row_" + new_index_tr + "_jumlah_1' value='1' readonly='readonly' /> </td>");
var action_delete = $("<td> <input class='btn btn-danger' type='button' id='row_" + new_index_tr + "_delete' class='delete' value='delete' /> </td>");
row.append(input);
row.append(action_delete);
row.append("</tr>");
$(".tbody").append(row);
});
$(document).on('click', "input[type='button'][id$='delete']",function(){
$(this).closest('tr').remove();
});
DEMO - I
Your remove method is incorrect. It should be:
$("#" + get_tr_parent_id).remove();
It was currently returning undefined instead of concatenating the two strings.

Categories