How to use jquery autocomplete in dynamically form input - javascript

I'm having an issue using jQuery autocomplete with dynamically created inputs. I can't get autocomplete to bind to the new inputs.
Form Table
<table class="table table-condensed" style="margin-left: 10px;">
<thead>
<tr>
<th width="250px">Nama</th>
<th width="100px">Kode</th>
<th width="100px">Harga</th>
<th width="100px">Jumlah</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' readonly name='harga_input[]' class='form-control' /></td>
<td><input name='jumlah_input[]' class='form-control' /></td>
<td></td>
</tr>
</tbody>
<tr>
<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>
script dynamically created inputs and autocmplete
<script>
$(function() {
$( "#nama" ).autocomplete({
source: "get_barang.php",
minLength: 2,
select: function( event, ui ) {
$('#kode').val(ui.item.kode);
$('#harga').val(ui.item.harga);
}
});
});
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 aksi = document.createElement('td');
// meng append element
itemlist.appendChild(row);
row.appendChild(nama);
row.appendChild(kode);
row.appendChild(harga);
row.appendChild(jumlah);
row.appendChild(aksi);
// membuat element input
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', 'kode');
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('id', 'harga');
harga_input.setAttribute('name', 'harga_input[]');
harga_input.setAttribute('readonly', '');
harga_input.setAttribute('class', 'form-control');
var jumlah_input = document.createElement('input');
jumlah_input.setAttribute('name', 'jumlah_input[]');
jumlah_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);
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);
};
i++;
}
</script>
Any advice?

You can use JS Math functions to create a random and unique id.. then you will need to call the autocomplete inside the function. Just repeat this process for each of your autocomplete methods.
var namaid = 'nama' + (Math.floor((1 + Math.random()) * 0x10000));
nama_input.setAttribute('id', namaid);
$("#" + namaid).autocomplete({
source: "get_barang.php",
minLength: 2,
select: function(event, ui) {
$('#kode').val(ui.item.kode);
$('#harga').val(ui.item.harga);
}
});
Handy tip: Since you're using jQuery, you can create elements with jQuery a lot easier than in vanilla JS.. have a look at this.

Related

Select box not changing while dynamically adding rows in a table

Hi iam able to add rows dynamically from the table below using javascript but the onchange function fired on the select box only works on the first row added how do you make it work for every row being added.Thanks.
<html>
<body>
<link href="style.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src='script.js'></script>
<table id="addProducts" border="1">
<tr>
<td>POI</td>
<td>Quantity</td>
<td>Price</td>
<td>Product</td>
<td>Add Rows?</td>
</tr>
<tr>
<td>1</td>
<td><input size=25 type="text" id="lngbox" readonly=true/></td>
<td><input size=25 type="text" id="price" readonly=true/></td>
<td>
<select name="selRow0" class="products">
<option value="value0">Product 1</option>
<option value="value1">Product 2</option>
</select>
</td>
<td><input type="button" id="delProducts" value="Delete" onclick="deleteRow(this)"/></td>
<td><input type="button" id="addmoreProducts" value="AddMore" onclick="insRow()"/></td>
</tr>
</table>
<div id="shw"></div>
</body>
</html>
$(function () {
$("select.products").on("change", function () {
var selected = $(this).val();
$("#price").val(selected);
})
});
function deleteRow(row)
{
var i = row.parentNode.parentNode.rowIndex;
document.getElementById('addProducts').deleteRow(i);
}
function insRow()
{
var x = document.getElementById('addProducts');
// deep clone the targeted row
var new_row = x.rows[1].cloneNode(true);
// get the total number of rows
var len = x.rows.length;
// set the innerHTML of the first row
new_row.cells[0].innerHTML = len;
// grab the input from the first cell and update its ID and value
var inp1 = new_row.cells[1].getElementsByTagName('input')[0];
inp1.id += len;
inp1.value = '';
// grab the input from the first cell and update its ID and value
var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
inp2.id += len;
inp2.value = '';
// append the new row to the table
x.appendChild(new_row);
}
I've updated your code. This should work now. Look at this jsfiddle:
JS:
$(function () {
$(document).on('change', 'select.products', function(){
var selected = $(this).val();
$(this).parents('tr').find('.price').val(selected);
});
$(document).on('click', '.addProduct', function(){
var ele = $(this).parents('tr').clone();
ele.find('input[type=text]').val('');
$(this).parents('tr').after(ele);
});
$(document).on('click', '.delProduct', function(){
if($(this).parents('table').find('tr').length > 2) {
$(this).parents('tr').remove();
}
});
});
Also I've updated your HTML:
<td><input size=25 type="text" class="lngbox" readonly=true/></td>
<td><input size=25 type="text" class="price" readonly=true/></td>
<td><input type="button" class="delProduct" value="Delete" /></td>
<td><input type="button" class="addProduct" value="AddMore" /></td>
Try this,
$("select.products").on("change", function(){
var selectedValue = $(this).val();
var td = $(this).parent();
(((td).parent()).children()[2].getElementsByTagName("input")[0]).value = selectedValue;
});

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

get selected value from dropdown on save

i am dynamically adding a row(with button and dropdown list) in table and each row is having edit save and delete button. onclick save button cell becomes non editable
function Save(){
var par = $(this).parent().parent(); //tr
var isactive = par.children("td:nth-child(1)");
var id = par.children("td:nth-child(2)");
isactive.html(id.children(':selected').val());
id.html(id.children("input[type=text]").val());
}
when i click on save button the id field becomes non-editable but dropdown is editable so can anyone please tell me the right way to do that.
function Edit(){
var par = $(this).parent().parent(); //tr
var isactive = par.children("td:nth-child(1)");
var id = par.children("td:nth-child(2)");
id.html("<input type='text' id='txtPhone' value='"+id.html()+"'/>");
}
and on click edit it takes the value of id to set in textbox but how to do the same with dropdown please help...
Dynamically Insert, Edit, Delete,Save Row in HTML table.
Here i created a Working jsFiddle. Refer the code in jsfiddle.
Html:
<div class="container">
<h2>Table Management</h2>
<div class="table-responsive">
<table border="1" class="table table-striped table-hover table-bordered">
<tr>
<td>Column 1</td>
<td>Column 2</td>
<td>Edit row</td>
<td>save</td>
<td class='deleterow'>delete<div class='glyphicon glyphicon-remove'></div></td>
</tr>
<tr>
<td>A</td>
<td>test1</td>
<td><a href='#' class='editrow'>edit</a></td>
<td><a href='#' class='saverow'>save</a></td>
<td class='deleterow'><div class='glyphicon glyphicon-remove'></div></td>
</tr>
<tr>
<td>B</td>
<td>test2</td> <td><a href='#' class='editrow'>edit</a></td>
<td><a href='#' class='saverow'>save</a></td>
<td class='deleterow'><div class='glyphicon glyphicon-remove'></div></td>
</tr>
</table>
</div>
</div>
<hr><button class='btn btn-lg btn-primary addnewrow pull-right'>Add New <span class="glyphicon glyphicon-plus"></span></button>
JS:
$(".deleterow").on("click", function(){
var $killrow = $(this).parent('tr');
$killrow.addClass("danger");
$killrow.fadeOut(2000, function(){
$(this).remove();
});
});
$(document).on('click',".saverow",function(){
var par = $(this).parent().parent(); //tr
var isactive = par.children("td:nth-child(1)");
var id = par.children("td:nth-child(2)");
isactive.html(isactive.children('select').val());
id.html(id.children("input[type=text]").val());
});
$(document).on("click",".editrow", function(){
var par = $(this).parent().parent(); //tr
var isactive = par.children("td:nth-child(1)");
var id = par.children("td:nth-child(2)");
var prevVal = isactive.html();
isactive.html("<select class='seldom'/>");
$('select.seldom')
.append($("<option>A</option>")
.attr("value","A")
.text('A'));
$('select.seldom')
.append($("<option>B</option>")
.attr("value","B")
.text('B'));
$('select.seldom option').each(function(){
if($(this).val() === prevVal){ // EDITED THIS LINE
$(this).attr("selected","selected");
}
});
id.html("<input type='text' id='txtPhone' value='"+id.html()+"'/>");
});
function Edit(){
var par = $(this).parent(); //tr
console.log(par);
var isactive = par.children("td:nth-child(1)");
var id = par.children("td:nth-child(2)");
console.log(id)
id.html("<input type='text' id='txtPhone' value='"+id.html()+"'/>");
}
$(".addnewrow").on("click", function(){
$('table tr:last').after("<tr><td data-qid='X'>NEW</td><td>NEW</td> <td><a href='#' class='editrow'>edit</a></td><td><a href='#' class='saverow'>save</a></td><td class='deleterow'><div class='glyphicon glyphicon-remove'></div></td></tr>");
});

Creating 2 html tables using javascript

I'm trying to create 2 dynamic html tables using Javascript with data from html inputs. I was able to create the first table I wanted but I've been unable to create 2 different tables using different inputs on the same page.
I tried changing the addRow() functions in the html and JS to have different names but this caused both tables to fail.
Any help would be appreciated. Here's the test code I've been using.
<!DOCTYPE html>
<body onload="load()">
<div id="myform">
<table>
<tr>
<td>Name:</td>
<td><input type="text" id="name"></td>
</tr>
<tr>
<td>Age:</td>
<td><input type="number" id="age">
<input type="button" id="add" value="Add" onclick="addRow()"></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</table>
<br>
<table>
<tr>
<td>Height:</td>
<td><input type="text" id="height"></td>
</tr>
<tr>
<td>Width:</td>
<td><input type="text" id="width">
<input type="button" id="addDim" value="Add" onclick="addRow()"></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</table>
</div>
<div id="mydata">
<table id="myTableData" border="1" cellpadding="2">
<tr>
<td> </td>
<td><b>Name</b></td>
<td><b>Age</b></td>
</tr>
</table>
<table id="myTableData2" border="1" cellpadding="2">
<tr>
<td> </td>
<td><b>Height</b></td>
<td><b>Width</b></td>
</tr>
</table>
</body>
</html>
function addRow() {
var myName = document.getElementById("name");
var age = document.getElementById("age");
var table = document.getElementById("myTableData");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML= '<input type="button" value = "Delete" onClick="deleteRow(this)">';
row.insertCell(1).innerHTML= myName.value;
row.insertCell(2).innerHTML= age.value;
var width = document.getElementById("width");
var height = document.getElementById("height");
var table2 = document.getElementById("myTableData2");
var rowCount2 = table2.rows.length;
var row2 = table2.insertRow(rowCount2);
row.insertCell(0).innerHTML = '<input type="button" value="Delete" onClick="deleteRow(this)">';
row.insertCell(1).innerHTML = width.value;
row.insertCell(2).innerHTML = height.value;
}
function deleteRow(obj) {
var index = obj.parentNode.parentNode.rowIndex;
var table = document.getElementById("myTableData");
table.deleteRow(index);
}
function load() {
console.log("Page load finished");
}
Looks like in the bottom section, you're not using the row2 variable you've defined.
Should be:
var rowCount2 = table2.rows.length;
var row2 = table2.insertRow(rowCount2);
row2.insertCell(0).innerHTML = '<input type="button" value="Delete" onClick="deleteRow(this)">';
row2.insertCell(1).innerHTML = width.value;
row2.insertCell(2).innerHTML = height.value;
here how i did it. you can use the same function for any amount of table, if pass the parameter in the function.
http://jsfiddle.net/8t5aqomk/2/
function myFunction(thisTable) {
var firstName = document.getElementById('firstName').value;
var lastName = document.getElementById('lastName').value;
var age = document.getElementById('age').value;
var info = [firstName,lastName,age]
var table = document.getElementById(thisTable);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cellCount = table.rows[0].cells.length;
for(var i=0; i<cellCount; i++) {
row.insertCell(i).innerHTML=info[i];
}
}

How to edit and delete the row in Javascript?

When I click table row, that row value will display the below text box, then I click + button to copy the first row values and insert new row and place value correctly.
When I click edit button # that value again place to first row. How to find that row index. How to get the particular ID?
<script>
function insRow()
{
var x=document.getElementById('scrolltable');
var new_row = x.rows[1].cloneNode(true);
var len = x.rows.length;
var code=document.getElementById('code').value;
var product=document.getElementById('product_name').value;
var qty=document.getElementById('quantity').value;
var rate=document.getElementById('amount').value;
var amount=document.getElementById('total').value;
var inp1 = new_row.cells[0].getElementsByTagName('input')[0];
inp1.id += len;
inp1.value = code;
var inp2 = new_row.cells[1].getElementsByTagName('input')[0];
inp2.id += len;
inp2.value = product;
var inp3 = new_row.cells[2].getElementsByTagName('input')[0];
inp3.id += len;
inp3.value = qty;
var inp4 = new_row.cells[3].getElementsByTagName('input')[0];
inp4.id += len;
inp4.value = rate;
var inp5 = new_row.cells[4].getElementsByTagName('input')[0];
inp5.id += len;
inp5.value = amount;
var button = new_row.cells[5].getElementsByTagName('input')[0];
button.value = "#";
button.onclick = function(it) {editRow(it)};
//cell4.appendChild(inp4);
x.appendChild( new_row );
document.getElementById('code').value='';
document.getElementById('product_name').value='';
document.getElementById('quantity').value='';
document.getElementById('amount').value='';
document.getElementById('total').value='';
document.getElementById('code').focus();
}
function deleteRow(row)
{
r=row.parentNode.parentNode;
r.parentNode.removeChild(r);
}
function editRow(evt) {
var x=document.getElementById('scrolltable');
//var l1 = evt.target.parentNode.parentNode;
//alert(l1);
var errorList = "";
var l=x.rows.length;
//var l=x.rowsIndex;
var y=l-1;
alert(l);
//alert("code"+y);
var code=document.getElementById('code'+y).value;
var product=document.getElementById('product_name'+y).value;
var qty=document.getElementById('quantity'+y).value;
var rate=document.getElementById('amount'+y).value;
var amount=document.getElementById('total'+y).value;
document.getElementById('code').value=code;
document.getElementById('product_name').value=product;
document.getElementById('quantity').value=qty;
document.getElementById('amount').value=rate;
document.getElementById('total').value=amount;
var i = evt.target.parentNode.parentNode.rowIndex;
document.getElementById('scrolltable').deleteRow(i);
}
</script>
My HTML code is:
<table class="table table-striped table-bordered dTableR" id="scrolltable">
<thead>
<tr>
<th width="10%">Code</th>
<th width="40%">Product</th>
<th width="10%">Total Qty</th>
<th width="10%">Rate</th>
<th width="12%">Amount</th>
<th width="10%">Action</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="code" class="span10" id="code" /></td>
<td><input type="text" name="product_name" class="span12" id="product_name" /></td>
<td><input type="text" name="quantity" class="span10" onBlur="calculate(this.value)" id="quantity" maxlength="8"/></td>
<td><input type="text" name="amount_name" class="span10" id="amount" /></td>
<td><input type="text" name="total_name" class="span10" id="total" maxlength="8" /></td>
<td><input type="button" id="addmorePOIbutton" style="width:25px;" value="+" onClick="insRow()"/>
<input type="button" id="delPOIbutton" style="width:25px;" value="-" onClick="deleteRow(this)"/></td>
</tr>
</tbody>
You can use jQuery for edit function :
First change
button.onclick = function(it) {editRow(it)};
to
button.onclick = function() {editRow(this)};
and change below function
function editRow(evt)
{
var $tr = $(evt).parents('tr'); // get parent tr
// put all values in top row
$('#code').val($tr.find('input[id^=code]').val());
$('#product_name').val($tr.find('input[id^=product_name]').val());
$('#quantity').val($tr.find('input[id^=quantity]').val());
$('#amount').val($tr.find('input[id^=amount]').val());
$('#total').val($tr.find('input[id^=total]').val());
// remove clicked tr
$tr.remove();
}
Working jsfiddle
Note : Please add jQuery js file to your html page.
since you are using jquery(as you have tagged this question with jquery), you can use index() function form jquery (http://api.jquery.com/index/).
Here is an updated (http://jsfiddle.net/6yXMF/) jsfiddle.
Which alerts index of the tr from which the input button is clicked.
Currently there are some issues in insertion and deletion or rows in your code. After resolving the issues you just can use the index function as demoed in
insRow() function.
Let me know if you have any queries.

Categories