I am trying to differentiate each id with their corresponding id from database. For Eg: Name_val19. The line var name=document.getElementById("name_val"+id).innerHTML; is returning null value. The value is being stored in database also
function edit_row(id)
{
var name=document.getElementById("name_val"+id).innerHTML;
var age=document.getElementById("age_val"+id).innerHTML;
document.getElementById("name_val"+id).innerHTML="<input type='text' id='name_text"+id+"' value='"+name+"'>";
document.getElementById("age_val"+id).innerHTML="<input type='text' id='age_text"+id+"' value='"+age+"'>";
document.getElementById("edit_button"+id).style.display="none";
document.getElementById("save_button"+id).style.display="block";
}
function save_row(id)
{
var name=document.getElementById("name_val"+id).value;
var age=document.getElementById("age_val"+id).value;
$.ajax
({
type:'post',
url:'modify_records.php',
data:{
edit_row:'edit_row',
row_id:id,
name_val:name,
age_val:age
},
success:function(response) {
if(response=="success")
{
document.getElementById("name_val"+id).innerHTML=name;
document.getElementById("age_val"+id).innerHTML=age;
document.getElementById("edit_button"+id).style.display="block";
document.getElementById("save_button"+id).style.display="none";
}
}
});
}
function delete_row(id)
{
$.ajax
({
type:'post',
url:'modify_records.php',
data:{
delete_row:'delete_row',
row_id:id,
},
success:function(response) {
if(response=="success")
{
var row=document.getElementById("row"+id);
row.parentNode.removeChild(row);
}
}
});
}
function insert_row()
{
var name=document.getElementById("new_name").value;
var age=document.getElementById("new_age").value;
$.ajax
({
type:'post',
url:'modify_records.php',
data:{
insert_row:'insert_row',
name_val:name,
age_val:age
},
success:function(response) {
if(response!="")
{
var id=response;
var table=document.getElementById("user_table");
var table_len=(table.rows.length)-1;
var row = table.insertRow(table_len).outerHTML="<tr id='row"+id+"'><td id='name_val"+id+"'>"+name+"</td><td id='age_val"+id+"'>"+age+"</td><td><input type='button' class='edit_button' id='edit_button"+id+"' value='Edit' onclick='edit_row("+id+");'/><input type='button' class='save_button' id='save_button"+id+"' value='Save' onclick='save_row("+id+");'/><input type='button' class='delete_button' id='delete_button"+id+"' value='Delete' onclick='delete_row("+id+");'/></td></tr>";
document.getElementById("new_name").value="";
document.getElementById("new_age").value="";
}
}
});
}
$("#insert").submit(function() {
var name= $("#new_name").val();
var password= $("#new_age").val();
$.ajax({
type: "POST",
url: "connect.php",
data: "name=" + name+ "&password=" + password,
success: function(data) {
alert("sucess");
}
});
});
PHP Code:
<html>
<head>
</head>
<body>
<div id="wrapper">
<table align="center" cellpadding="10" border="1" id="user_table">
<tr>
<th>NAME</th>
<th>AGE</th>
<th></th>
</tr>
<?php
include "connect.php";
$select=mysqli_query($connection,"SELECT * FROM user_detail");
if($select!=NULL){
while ($row=mysqli_fetch_array($select,MYSQLI_BOTH))
{
?>
<tr id="row<?php echo $row['id'];?>">
<td id="name_val<?php echo row['id'];?>"><?php echo $row['name'];?></td>
<td id="age_val<?php echo $row['id'];?>"><?php echo $row['age'];?></td>
<td>
<button class="edit_button" id="edit_button<?php echo $row['id'];?>" onclick="edit_row('<?php echo $row['id'];?>');">Edit</button>
<button class="save_button" id="save_button<?php echo $row['id'];?>" onclick="save_row('<?php echo $row['id'];?>');">Save</button>
<button class="delete_button" id="delete_button<?php echo $row['id'];?>" onclick="delete_row('<?php echo $row['id'];?>');">Delete</button>
</td>
</tr>
<?php
}
}
?>
<tr id="new_row"><form id="insert" onclick="insert_db()">
<td><input type="text" id="new_name"></td>
<td><input type="text" id="new_age"></td>
<td><button type="button" value="Insert Row" onclick="insert_row()">Insert</button></td>
</form></tr>
</table>
</div>
</body>
<script type="text/javascript" src="./js/jquery-3.2.0.js"></script>
<script type="text/javascript" src="./js/modify_records.js"></script>
</html>
looks like a few things, first i recommend getting the element by class since your id is complicated, try using getElementByClass("edit_button") to get <button class="edit_button" id="...">
getElementById() does exactly that, you are trying to get a dom (html) element by its id="" attribute, into the js Scope so you can do something with it. it should be getElementById("IDofElement")
getElementById("row") gets <p id="row"> </p>
but it looks like you set
var id=response; which makes your
getElementById("IDofElement"+"ENTIRE AJAX RESPONSE") call throw an error because there is no dom element with an id of e.g.
<div id="rowENTIRE-AJAX-RESPONSE"></div>
You're killing yourself with all these IDs. Use HTML5 data-attribute to store your record's ID once per row.
<tr data-id="<?php echo $row['id'] ?>">
<!-- added class names to cells bc we'll be using them later -->
<td class="name"><?php echo $row['name'] ?></td>
<td class="age"><?php echo $row['age'] ?></td>
<td>
<button type="button" class="edit_button">Edit</button>
<button type="button" class="save_button">Save</button>
<button type="button" class="delete_button">Delete</button>
</td>
</tr>
Utilize jQuery to its full potential to find elements (e.g. .find() and .closest()) and attach event handlers. document.getElementById and onclick attributes are so passé when it comes to jQuery.
Your code can be cleaner:
$('.edit_button').click(function () {
var tr = $(this).closest('tr'),
tdName = tr.find('td.name'),
tdAge = tr.find('td.age');
var id = tr.data('id'),
name = tdName.text(),
age = tdAge.text();
tdName.html('<input type="text" name="name" value="' + name + '">');
tdAge.html('<input type="text" name="age" value="' + age + '">');
tr.find('.edit_button').hide();
tr.find('.save_button').show();
});
$('.save_button').click(function () {
var tr = $(this).closest('tr'),
tdName = tr.find('td.name'),
tdAge = tr.find('td.age');
var id = tr.data('id'),
name = tdName.find('input').val(),
age = tdAge.find('input').val();
// shorthand method for $.ajax POST
$.post('modify_records.php', {
edit_row: 'edit_row',
row_id: id,
name_val: name,
age_val: age
}, function (response) {
if (response == "success") {
tdName.html(name);
tdAge.html(age);
tr.find('.edit_button').show();
tr.find('.save_button').hide();
}
});
});
$('.delete_button').click(function () {
var tr = $(this).closest('tr')
var id = tr.data('id');
$.post('modify_records.php', { delete_row: 'delete_row', row_id: id }, function (response) {
if (response == "success") {
tr.remove();
}
});
});
Quick demo
$('.edit_button').click(function() {
var tr = $(this).closest('tr'),
tdName = tr.find('td.name'),
tdAge = tr.find('td.age');
var id = tr.data('id'),
name = tdName.text(),
age = tdAge.text();
tdName.html('<input type="text" name="name" value="' + name + '">');
tdAge.html('<input type="text" name="age" value="' + age + '">');
tr.find('.edit_button').hide();
tr.find('.save_button').show();
});
$('.save_button').click(function() {
var tr = $(this).closest('tr'),
tdName = tr.find('td.name'),
tdAge = tr.find('td.age');
var id = tr.data('id'),
name = tdName.find('input').val(),
age = tdAge.find('input').val();
console.log('saving', id, name, age)
$.post('modify_records.php', {
edit_row: 'edit_row',
row_id: id,
name_val: name,
age_val: age
}, function(response) {
if (response == "success") {
tdName.html(name);
tdAge.html(age);
tr.find('.edit_button').show();
tr.find('.save_button').hide();
}
});
});
$('.delete_button').click(function() {
var tr = $(this).closest('tr')
var id = tr.data('id');
console.log('deleting', id)
$.post('modify_records.php', {
delete_row: 'delete_row',
row_id: id
}, function(response) {
if (response == "success") {
tr.remove();
}
});
});
.save_button {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr data-id="1">
<td class="name">Bill</td>
<td class="age">21</td>
<td>
<button type="button" class="edit_button">Edit</button>
<button type="button" class="save_button">Save</button>
<button type="button" class="delete_button">Delete</button>
</td>
</tr>
<tr data-id="2">
<td class="name">Sarah</td>
<td class="age">22</td>
<td>
<button type="button" class="edit_button">Edit</button>
<button type="button" class="save_button">Save</button>
<button type="button" class="delete_button">Delete</button>
</td>
</tr>
<tr data-id="3">
<td class="name">Jean</td>
<td class="age">34</td>
<td>
<button type="button" class="edit_button">Edit</button>
<button type="button" class="save_button">Save</button>
<button type="button" class="delete_button">Delete</button>
</td>
</tr>
</table>
Related
Hello i have problem with my project, i try to JSON but i have multiple variable so i dont know if it works, and when i try passing $id into controller snap and calling data using mysql items data is null. im stuck at here
here my view
<div class="row">
<table class="table mt-3" id="t_detail">
<thead class="thead">
<tr>
<th scope="col">#</th>
<th scope="col">Gambar</th>
<th scope="col">Nama Barang</th>
<th scope="col">Harga</th>
</tr>
</thead>
<tbody>
<?php $no=0;foreach ($produk as $id=>$prd): ?>
<?php $no++?>
<tr>
<?php $barang []= array(
'id' => $prd->id_barang,
'quantity' => 1,
'price' => $prd->harga,
'name' => $prd->nama_barang,
);?>
<th scope="row"><?=$no?></th>
<td><img height="280" width="auto" src="<?=base_url('uploads/' . $prd->gambar)?>" ></td>
<td><?=$prd->nama_barang?></td>
<td>Rp. <?php echo number_format($prd->harga,0,",",".");?></td>
</tr>
<?php endforeach;?>
<?php $no++?>
<tr>
<th scope="row"><?=$no?></th>
<td></td>
<td>Biaya Ongkir</td>
<td>Rp. <?php echo number_format($transaksi->ongkir,0,",",".");?></td>
</tr>
</tbody>
<tfoot>
<tr>
<th scope="row"></th>
<td></td>
<td>Total Bayar</td>
<td>Rp. <?php echo number_format($transaksi->total_bayar,0,",",".");?></td>
</tr>
</tfoot>
</table>
</div>
<?php if ($produk):?>
<div class="row">
<div class="col-md-6 offset-md-6">
<button class="btn btn-sm btn-success float-right" id="tombol-bayar">Bayar</button>
</div>
</div>
<?php endif;?>
<input name="transaksi_id" value="<?=($transaksi->id)?>" type="hidden">
<input name="nama" value="<?=($transaksi->namalengkap)?>" type="hidden">
<input name="alamat" value="<?=($transaksi->alamat)?>" type="hidden">
<input name="kodepos" value="<?=($transaksi->kodepos)?>" type="hidden">
<input name="kabupaten" value="<?=($transaksi->kabupaten)?>" type="hidden">
<input name="no_hp" value="<?=($user['no_hp'])?>" type="hidden">
<input name="email" value="<?=($user['email'])?>" type="hidden">
<input name="total_bayar" value="<?=($transaksi->total_bayar)?>" type="hidden">
<input name="ongkir" value="<?=($transaksi->ongkir)?>" type="hidden">
<input name="ekspedisi" value="<?=($transaksi->ekspedisi)?>" type="hidden">
<input name="paket" value="<?=($transaksi->paket)?>" type="hidden">
and my JS
<script>
$('#tombol-bayar').click(function(event) {
var transaksi_id = $("input[name=transaksi_id]").val();
var nama = $("input[name=nama]").val();
var alamat = $("input[name=alamat]").val();
var email = $("input[name=email]").val();
var kodepos = $("input[name=kodepos]").val();
var ongkir = $("input[name=ongkir]").val();
var ekspedisi = $("input[name=ekspedisi]").val();
var paket = $("input[name=paket]").val();
var kabupaten = $("input[name=kabupaten]").val();
var no_hp = $("input[name=no_hp]").val();
var total_bayar = $("input[name=total_bayar]").val();
$(this).attr("disabled", "disabled");
$.ajax({
type: "POST",
url: '<?= base_url() ?>/snap/token',
cache: false,
data: {
barang: barang,
'transaksi_id': transaksi_id,
'nama': nama,
'alamat': alamat,
'email': email,
'kodepos': kodepos,
'ongkir': ongkir,
'ekspedisi': ekspedisi,
'paket': paket,
'kabupaten': kabupaten,
'no_hp': no_hp,
'total_bayar': total_bayar,
},
success: function(data) {
//location = data;
console.log('token = ' + data);
var resultType = document.getElementById('result-type');
var resultData = document.getElementById('result-data');
function changeResult(type, data) {
$("#result-type").val(type);
$("#result-data").val(JSON.stringify(data));
//resultType.innerHTML = type;
//resultData.innerHTML = JSON.stringify(data);
}
snap.pay(data, {
onSuccess: function(result) {
changeResult('success', result);
console.log(result.status_message);
console.log(result);
$("#payment-form").submit();
},
onPending: function(result) {
changeResult('pending', result);
console.log(result.status_message);
$("#payment-form").submit();
},
onError: function(result) {
changeResult('error', result);
console.log(result.status_message);
$("#payment-form").submit();
}
});
}
});
});
and my controller
public function token()
{
$nama = $this->input->post('nama');
$email = $this->input->post('email');
$kabupaten = $this->input->post('kabupaten');
$kodepos = $this->input->post('kodepos');
$alamat = $this->input->post('alamat');
$no_hp = $this->input->post('no_hp');
$ekspedisi = $this->input->post('ekspedisi');
$paket = $this->input->post('paket');
$ongkir = $this->input->post('ongkir');
$total_bayar = $this->input->post('total_bayar');
$barang = $this->input->post('barang');
$item_details [] = $barang;
how can i post items data into that controller.. im confuse please help
I want to add new data to the main table using the checkbox option, but the data added is not the same as the selected data. this is my code ...
<table border="1" id="table2">
<tr>
<td>Raka</td>
<input type="hidden" id="fname" value="Raka">
<td>Gilbert</td>
<input type="hidden" id="lname" value="Gilbert">
<td><input type="checkbox" name="chk"></td>
</tr>
<tr>
<td>Achyar</td>
<input type="hidden" id="fname" value="Achyar">
<td>Lucas</td>
<input type="hidden" id="lname" value="Lucas">
<td><input type="checkbox" name="chk"></td>
</tr>
</table>
<script>
$(document).on('click', '#Add', function() {
$("table").find('input[name="chk"]').each(function(){
if($(this).is(":checked")){
var fname = $('#fname').val();
var lname = $('#lname').val();
var newData = '<tr>'+
'<td>'+fname+'</td>'+
'<td>'+lname+'</td>'+
'<tr>';
$('table').append(newData);
}
});
})
</script>
You need to change your id="fname" to class="fname" and get the input value closest to checkbox. Currently you are getting data from the first inputs as they have the same id's.
function valueExists(value) {
if (!value) {
return true;
}
let exists = false;
$("#main-table").find('tr').each(function() {
let fname = $(this).find("td:nth-child(1)").text(),
lname = $(this).find("td:nth-child(2)").text();
const fullName = `${fname}${lname}`;
if (value.toLowerCase() === fullName.toLowerCase()) {
exists = true;
}
});
return exists;
}
$(document).on('click', '#add', function() {
$("table").find('input[name="chk"]').each(function(e) {
if ($(this).is(":checked")) {
var fname = $(this).parents('tr').find('.fname').val();
var lname = $(this).parents('tr').find('.lname').val();
if (valueExists(`${fname}${lname}`)) return;
var newData = '<tr>' +
'<td>' + fname + '</td>' +
'<td>' + lname + '</td>' +
'<tr>';
$('#main-table').append(newData);
}
});
})
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Main Table</h1>
<table class="table table-dark" border="1" id="main-table">
</table>
<hr>
<h1>Second table</h1>
<table border="1" id="table2">
<tr>
<td class="name">Raka</td>
<input type="hidden" class="fname" value="Raka">
<td class="last">Gilbert</td>
<input type="hidden" class="lname" value="Gilbert">
<td><input class="check" type="checkbox" name="chk"></td>
</tr>
<tr>
<td class="name">Achyar</td>
<input type="hidden" class="fname" value="Achyar">
<td class="last">Lucas</td>
<input type="hidden" class="lname" value="Lucas">
<td><input class="check" type="checkbox" name="chk"></td>
</tr>
</table>
<button type="button" id="add" name="button">Add</button>
Try this. I have used plain javascript
document.addEventListener("click", function() {
[...document.querySelectorAll("input[name='chk']")].forEach(data => {
console.log(data);
if (data.checked) {
const fname = document.getElementById("fname").value;
const lname = document.getElementById("lname").value;
const newData = `<tr><td>${ fname }</td><td>${ lname }</td</tr>`;
// "<tr>" + "<td>" + fname + "</td>" + "<td>" + lname + "</td>" + "<tr>";
document.getElementById("table2").innerHTML += newData;
}
});
});
Hope was useful. If any flaws please update
Here is a neater solution, using 2 tables as requested, without hidden inputs and a better use of 'tables' and 'trs' in jquery
$(function(){
$("#btnAdd").click(function(){
let table1 = $("#table1");
table2 = $("#table2");
$.each(table2.find('tr'), function(i, tr){
tr = $(tr);
let new_tr = $('<tr>');
if (tr.find("td input").is(":checked")) {
let fname = tr.find("td:nth-child(1)").html(),
lname = tr.find("td:nth-child(2)").html();
new_tr.append(
'<td>' + fname + '</td>' +
'<td>' + lname + '</td>' +
'<td><input type="checkbox" name="chk"></td>'
);
table1.append(new_tr)
}
})
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
TABLE 1
<table border="1" id="table1">
</table>
<hr/>
TABLE 2
<table border="1" id="table2">
<tr>
<td>Raka</td>
<td>Gilbert</td>
<td><input type="checkbox" name="chk"></td>
</tr>
<tr>
<td>Achyar</td>
<td>Lucas</td>
<td><input type="checkbox" name="chk"></td>
</tr>
</table>
<button type="button" id="btnAdd">Add</button>
I tried to send information via ajax about user_question and language input fields, but how to write correctly this element inside ajax javascript to save the table element value in database.
thank you.
the script element.
<table id="myTable" class="table table-sm table-hover order-list">
<thead>
<tr>
<td>User Question</td>
<td>Language</td>
</tr>
</thead>
<tbody>
<tr>
<td class="col-md-9">' . HTML::inputField('user_question', null, 'placeholder="Write a short answer"'). '</td>
<td class="col-md-2">' . HTML::inputField('language', null, 'placeholder="Language"') . '</td>
<td class="col-sm-1"><a id="delete_row" class="deleteRow"></a></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5">
<input type="button" class="btn btn-lg btn-block " id="addrow" value="Add Row" />
</td>
</tr>
<tr></tr>
</tfoot>
</table>
<script>
$(document).ready(function () {
var counter = 0;
$("#addrow").on("click", function () {
var newRow = $("<tr>");
var cols = "";
cols += '<td><input type="text" class="form-control" name="user_question' + counter + '"/></td>';
cols += '<td><input type="text" class="form-control" name="language' + counter + '"/></td>';
cols += '<td><input type="button" class="ibtnDel btn btn-md btn-danger " value="Delete"></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
counter++;
// element pb
// var data = $("#new_product").serialize(); // form id or table id ?
var dataString = 'user_question='+user_question+'language='+language;
$.ajax({
type: 'POST',
url: '{$ajax_url}',
data : dataString,
success: function(data) {
alert(data);
$("p").text(data);
}
});
$("table.order-list").on("click", ".ibtnDel", function (event) {
$(this).closest("tr").remove();
counter -= 1
});
});
</script>
Use like this to get php variables value inside javascript in .php page
url: "<?php echo $ajax_url; ?>",
Also use & and symbol to add two or more param in your dataString
I am facing problems in:
the function saveRow does not save the row. I get this error:
Uncaught TypeError: Cannot set property name of undefined at at saveRow at HTMLInputElement.onclick.
2) the deleteRow does not work. I get a similar error:
Uncaught TypeError: Cannot set property 'innerHTML' of null.
3) in the editRow, I fields to become editable, but with the default values as what was saved before. For example, the list is always A, B, C which is not what I want. I want the initial value of the list to be what was selected previously.
There should be something wrong I am doing. Here is the code:
HTML:
<html>
<head>
</head>
<body>
<div id="wrapper">
<table align='center' cellspacing=2 cellpadding=5 id="data_table" border=1>
<thead>
<tr>
<th>Name</th>
<th>Level</th>
<th>Action</th>
</tr>
</thead>
<tbody id="table-rows">
<tr>
<td><input type="text" id="name-text"></td>
<td>
<select name="levels-list" id="levels-list">
<option value="A" id="option-1">A</option>
<option value="B" id="option-2">B</option>
<option value="C" id="option-3">C</option>
</select>
</td>
<td><input type="button" class="add" value="Add Row" id="add-button"></td>
</tr>
</tbody>
</table>
</div>
<script src="get-text.js"></script>
</body>
</html>
The script:
var myArray = [{
"name": "aaa",
"level": "A"
}, {
"name": "bbb",
"level": "B"
}, {
"name": "ccc",
"level": "C"
}];
display();
function display() {
var length = myArray.length;
var htmlText = "";
for (var i = 0; i < length; i++) {
htmlText +=
"<tr id='row" + i + "'>\
<td>" + myArray[i].name + "</td>\
<td>" + myArray[i].level + "</td>\
<td>\
<input type='button' id='edit_button" + i + "' value='Edit' class='edit' onclick='editRow("+i+")'> \
<input type='button' id='save_button" + i + "' value='Save' class='save' onclick='save_row(" + i + ")'> \
<input type='button' value='Delete' class='delete' onclick='delete_row(" + i + ")'>\
</td>\
</tr>";
}//end loop
htmlText+=
"<tr>\
<td><input type='text' id='name-text'></td>\
<td>\
<select name='levels-list' id='levels-list'>\
<option value='A' id='option-1'>A</option>\
<option value='B' id='option-2'>B</option>\
<option value='C' id='option-3'>C</option>\
</select>\
</td>\
<td><input type='button' class='add' value='Add Row' id='add-button' ></td>\
</tr>";
document.getElementById("table-rows").innerHTML = htmlText;
}//end display
var addButton=document.getElementById("add-button");
addButton.addEventListener('click', addRow, false);
function addRow(){
event.preventDefault();
var newData= document.getElementById("name-text").value;
var newLevel = document.getElementById("levels-list").value;
var table = document.getElementById("data_table");
var tableLength = (table.rows.length)-1;
// console.log(tableLength);
var row = table.insertRow(tableLength).innerHTML=
"<tr id= 'row"+tableLength+"'>\
<td id='name-text"+tableLength+"'>"+newData+"</td>\
<td id='levels-list"+tableLength+"'>"+newLevel+"</td>\
<td><input type='button' id='edit-button"+tableLength+"' value='Edit' class='edit' onclick='editRow("+tableLength+")'> \
<input type='button' id='save-button"+tableLength+"' value='Save' class='save' onclick='saveRow("+tableLength+")'> \
<input type='button' id= 'delete-button"+tableLength+"' value='Delete' class='delete' onclick='deleteRow("+tableLength+")'>\
</td>\
</tr>";
document.getElementById("name-text").value="";
}//end addRow
function editRow(no)
{
document.getElementById("edit-button"+no).disabled=true;
//document.getElementById("save-button"+no).style.display="block";
var name=document.getElementById("name-text"+no);
var level=document.getElementById("levels-list"+no);
var nameData=name.innerHTML;
var levelData=level.innerHTML;
name.innerHTML="<input type='text' id='name_text"+no+"' value='"+nameData+"'>";
level.innerHTML='<select id="levels-list'+no+'">\
<option value="A" id="option-1">A</option>\
<option value="B" id="option-2">B</option>\
<option value="C" id="option-3">C</option>\
</select>' ;
document.getElementById("levels-list"+no).value = levelData;
}
function deleteRow(no) {
myArray.splice(no, 1);
document.getElementById("row"+no).innerHTML="";
//display();
} //end deleteRow
function saveRow(no)
{
myArray[no].name = document.getElementById("name-text"+no).value;
myArray[no].level = document.getElementById("levels-list"+no).value;
document.getElementById("row"+no).innerHTML =
"<tr id= 'row"+no+"'>\
<td id='name-text"+no+"'>"+myArray[no].name+"</td>\
<td id='levels-list"+no+"'>"+myArray[no].level+"</td>\
<td><input type='button' id='edit-button"+no+"' value='Edit' class='edit' onclick='editRow("+no+")'> \
<input type='button' value='Delete' class='delete' onclick='deleteRow("+no+")'>\
</td>\
</tr>";
}//end saveRow
I refactored a bit your code and created a new jsfiddle. You can refactor it more and more, and if possible to insert jQuery in your project, you will simply it a lot more.
So few notes:
1) Keep you model up to date with your UI changes. In the before sample you were manipulating HTML but you were not updating the array model
2) Try to keep your common code in functions, in order to avoid repetitions.
For example I moved the logic for creating row inside a function, and just calling that function every time that you need to create a new row (for displaying at the beginning and when clicking add row)
3) When you call your functions in the row, pass also the current HTML element. You can pass it in order to know which current HTML element has been clicked, so that you can easily manipulate that row.
4) Use two tbodies. One for the data and another one for the actions. It makes easier to distinct data from actions, avoiding to repeat every time also that row for actions
And few other things that you can check alone with the code.
You have to manage just the logic of disabling the buttons in the right operations, in order to avoid for example to click edit again when editing, but it would be a good exercise to do it yourself :)
Here the sample:
var myArray = [{
"name": "aaa",
"level": "A"
}, {
"name": "bbb",
"level": "B"
}, {
"name": "ccc",
"level": "C"
}];
function createDataRow(el, ind) {
var row = document.createElement('tr');
row.id = 'row-' + ind;
var cell1Content = `
<div class="name-content">${el.name}</div>
<input class="name-edit" type="text" id="name-text-${ind}" value="${el.name}" style="display:none;">
`;
var cell2Content = `
<div class="level-content">${el.level}</div>
<select class="level-edit" id="levels-list-${ind}" style="display:none;">
<option value="A">A</option>\
<option value="B">B</option>\
<option value="C">C</option>\
</select>
`;
var cell3Content = `
<input type="button" id='edit_button" + i + "' value="Edit" class="edit" onclick="editRow(this, ${ind})">
<input type="button" id='save_button" + i + "' value="Save" class="save" onclick="saveRow(this, ${ind})">
<input type="button" value="Delete" class="delete" onclick="deleteRow(this, ${ind})">
`;
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = cell1Content;
cell2.innerHTML = cell2Content;
cell3.innerHTML = cell3Content;
document.getElementById('table-data').appendChild(row);
}
function displayData() {
myArray.forEach(function(el, ind) {
createDataRow(el,ind);
});
}
function deleteRow(el, ind) {
el.parentElement.parentElement.parentElement.removeChild(el.parentElement.parentElement);
myArray.splice(ind, 1);
}
function addRow(){
event.preventDefault();
var newEl = {
"name": document.getElementById("name-text").value,
"level": document.getElementById("levels-list").value
};
myArray.push(newEl);
createDataRow(newEl, myArray.length - 1);
document.getElementById("name-text").value = '';
document.getElementById("levels-list").value = 'A';
}//end addRow
function editRow(el, ind)
{
var currentRow = el.parentElement.parentElement;
currentRow.cells[0].getElementsByClassName("name-content")[0].style.display = 'none';
currentRow.cells[0].getElementsByClassName("name-edit")[0].style.display = 'block';
currentRow.cells[1].getElementsByClassName("level-content")[0].style.display = 'none';
currentRow.cells[1].getElementsByClassName("level-edit")[0].value = myArray[ind].level;
currentRow.cells[1].getElementsByClassName("level-edit")[0].style.display = 'block';
}
//end deleteRow
function saveRow(el, ind)
{
var currentRow = el.parentElement.parentElement;
var nameContent = currentRow.cells[0].getElementsByClassName("name-content")[0];
var nameEdit = currentRow.cells[0].getElementsByClassName("name-edit")[0];
nameContent.innerHTML = nameEdit.value;
nameContent.style.display = 'block';
nameEdit.style.display = 'none';
var levelContent = currentRow.cells[1].getElementsByClassName("level-content")[0];
var levelEdit = currentRow.cells[1].getElementsByClassName("level-edit")[0];
levelContent.innerHTML = levelEdit.value;
levelContent.style.display = 'block';
levelEdit.style.display = 'none';
myArray[ind].name = nameEdit.value;
myArray[ind].level = levelEdit.value;
}//end saveRow
var addButton=document.getElementById("add-button");
addButton.addEventListener('click', addRow, false);
displayData();
<body>
<div id="wrapper">
<table align='center' cellspacing=2 cellpadding=5 id="data_table" border=1>
<thead>
<tr>
<th>Name</th>
<th>Level</th>
<th>Action</th>
</tr>
</thead>
<tbody id="table-data">
</tbody>
<tbody id="table-rows">
<tr>
<td><input type="text" id="name-text"></td>
<td>
<select name="levels-list" id="levels-list">
<option value="A" id="option-1">A</option>
<option value="B" id="option-2">B</option>
<option value="C" id="option-3">C</option>
</select>
</td>
<td><input type="button" class="add" value="Add Row" id="add-button"></td>
</tr>
</tbody>
</table>
</div>
</body>
And here the jsfiddle (this time saved :D ):
https://jsfiddle.net/u0865zaa/8/
I hope it helps. For any queries let me know.
I have the following data table where it has 2 control buttons, edit and save. The issue I am having is hiding the save button from the first preview.
(The output I am trying to achieve is on the first page it should only display Edit and when a user clicks on Edit it should display save.)
please see the snippet for further explanation.
function edit_row(id)
{
var name=document.getElementById("name_val"+id).innerHTML;
var age=document.getElementById("age_val"+id).innerHTML;
document.getElementById("name_val"+id).innerHTML="<input type='text' id='name_text"+id+"' value='"+name+"'>";
document.getElementById("age_val"+id).innerHTML="<input type='text' id='age_text"+id+"' value='"+age+"'>";
document.getElementById("edit_button"+id).style.display="none";
document.getElementById("save_button"+id).style.display="block";
}
function save_row(id)
{
var name=document.getElementById("name_text"+id).value;
var age=document.getElementById("age_text"+id).value;
$.ajax
({
type:'post',
url:'modify_records.php',
data:{
edit_row:'edit_row',
row_id:id,
name_val:name,
age_val:age
},
success:function(response) {
if(response=="success")
{
document.getElementById("name_val"+id).innerHTML=name;
document.getElementById("age_val"+id).innerHTML=age;
document.getElementById("edit_button"+id).style.display="block";
document.getElementById("save_button"+id).style.display="none";
}
}
});
}
function delete_row(id)
{
$.ajax
({
type:'post',
url:'modify_records.php',
data:{
delete_row:'delete_row',
row_id:id,
},
success:function(response) {
if(response=="success")
{
var row=document.getElementById("row"+id);
row.parentNode.removeChild(row);
}
}
});
}
function insert_row()
{
var name=document.getElementById("new_name").value;
var age=document.getElementById("new_age").value;
$.ajax
({
type:'post',
url:'modify_records.php',
data:{
insert_row:'insert_row',
name_val:name,
age_val:age
},
success:function(response) {
if(response!="")
{
var id=response;
var table=document.getElementById("user_table");
var table_len=(table.rows.length)-1;
var row = table.insertRow(table_len).outerHTML="<tr id='row"+id+"'><td id='name_val"+id+"'>"+name+"</td><td id='age_val"+id+"'>"+age+"</td><td><input type='button' class='edit_button' id='edit_button"+id+"' value='edit' onclick='edit_row("+id+");'/><input type='button' class='save_button' id='save_button"+id+"' value='save' onclick='save_row("+id+");'/><input type='button' class='delete_button' id='delete_button"+id+"' value='delete' onclick='delete_row("+id+");'/></td></tr>";
document.getElementById("new_name").value="";
document.getElementById("new_age").value="";
}
}
});
}
<table align="center" cellpadding="10" border="1" id="user_table">
<tr>
<th>NAME</th>
<th>AGE</th>
<th></th>
</tr>
<tr id="">
<td id="name_val">Test Name</td>
<td id="age_val">Test Age</td>
<td>
<input type='button' class="edit_button" id="edit_button" value="edit" onclick="edit_row('');">
<input type='button' class="save_button" id="save_button" value="save" onclick="save_row('');">
</tr>
<?php
}
?>
</table>
Just add this css.
.save_button{
display: none;
}
or go for inline css style="display:none" for first display.
function edit_row(id)
{
var name=document.getElementById("name_val"+id).innerHTML;
var age=document.getElementById("age_val"+id).innerHTML;
document.getElementById("name_val"+id).innerHTML="<input type='text' id='name_text"+id+"' value='"+name+"'>";
document.getElementById("age_val"+id).innerHTML="<input type='text' id='age_text"+id+"' value='"+age+"'>";
document.getElementById("edit_button"+id).style.display="none";
document.getElementById("save_button"+id).style.display="block";
}
function save_row(id)
{
var name=document.getElementById("name_text"+id).value;
var age=document.getElementById("age_text"+id).value;
$.ajax
({
type:'post',
url:'modify_records.php',
data:{
edit_row:'edit_row',
row_id:id,
name_val:name,
age_val:age
},
success:function(response) {
if(response=="success")
{
document.getElementById("name_val"+id).innerHTML=name;
document.getElementById("age_val"+id).innerHTML=age;
document.getElementById("edit_button"+id).style.display="block";
document.getElementById("save_button"+id).style.display="none";
}
}
});
}
function delete_row(id)
{
$.ajax
({
type:'post',
url:'modify_records.php',
data:{
delete_row:'delete_row',
row_id:id,
},
success:function(response) {
if(response=="success")
{
var row=document.getElementById("row"+id);
row.parentNode.removeChild(row);
}
}
});
}
function insert_row()
{
var name=document.getElementById("new_name").value;
var age=document.getElementById("new_age").value;
$.ajax
({
type:'post',
url:'modify_records.php',
data:{
insert_row:'insert_row',
name_val:name,
age_val:age
},
success:function(response) {
if(response!="")
{
var id=response;
var table=document.getElementById("user_table");
var table_len=(table.rows.length)-1;
var row = table.insertRow(table_len).outerHTML="<tr id='row"+id+"'><td id='name_val"+id+"'>"+name+"</td><td id='age_val"+id+"'>"+age+"</td><td><input type='button' class='edit_button' id='edit_button"+id+"' value='edit' onclick='edit_row("+id+");'/><input type='button' class='save_button' id='save_button"+id+"' value='save' onclick='save_row("+id+");'/><input type='button' class='delete_button' id='delete_button"+id+"' value='delete' onclick='delete_row("+id+");'/></td></tr>";
document.getElementById("new_name").value="";
document.getElementById("new_age").value="";
}
}
});
}
.save_button{
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table align="center" cellpadding="10" border="1" id="user_table">
<tr>
<th>NAME</th>
<th>AGE</th>
<th></th>
</tr>
<tr id="">
<td id="name_val">Test Name</td>
<td id="age_val">Test Age</td>
<td>
<input type='button' class="edit_button" id="edit_button" value="edit" onclick="edit_row('');">
<input type='button' class="save_button" id="save_button" value="save" onclick="save_row('');">
</tr>
<?php
}
?>
</table>
Initially set the display:none for the Save button in your HTML Code like this following code,
<input type='button' class="edit_button" id="edit_button" value="edit"
onclick="edit_row('');" style="display:block;">
<input type='button' class="save_button" id="save_button" value="save"
onclick="save_row('');" style="display:none;">