I create a table with CRUD operations in jQuery. All CRUD operations worked, no issues with them. I need to store the every uploaded data in local storage. When I add data to the table, the data is stored in the local storage. But when I added one more data to the table, the first data was deleted automatically in local storage. Local storage displays only current data. If I made any changes to the table, local storage data wouldn't be updated. Please help me to solve the issue.
<!DOCTYPE html>
<html lang="en">
<head>
<title>CRUD Table jQuery</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12 text-right">
<input type="button" id="btnAdd" class="btn btn-primary para" value="Add New" />
</div>
</div>
<div class="row pt-3">
<div class="col-md-12 col-sm-12 col-12 p-2 ">
<table id="tblData" class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Address</th>
<th>Age</th>
<th class="tdaction">Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
<script>
var emptyRow = "<tr><td colspan='4' class='text-center'></td></tr>";
var emptyNewRow = "<tr class='trNewRow'>";
emptyNewRow = emptyNewRow + " <td class='tdID'>";
emptyNewRow = emptyNewRow + " <input type='text' class='form-control txtID' />";
emptyNewRow = emptyNewRow + " </td>";
emptyNewRow = emptyNewRow + " <td class='tdName'>";
emptyNewRow = emptyNewRow + " <input type='text' class='form-control txtName' />";
emptyNewRow = emptyNewRow + " </td>";
emptyNewRow = emptyNewRow + " <td class='tdAddress'>";
emptyNewRow = emptyNewRow + " <input type='text' class='form-control txtAddress' />";
emptyNewRow = emptyNewRow + " </td>";
emptyNewRow = emptyNewRow + " <td class='tdAge'>";
emptyNewRow = emptyNewRow + " <input type='text' class='form-control txtAge' />";
emptyNewRow = emptyNewRow + " </td>";
emptyNewRow = emptyNewRow + " <td class='tdAction'>";
emptyNewRow = emptyNewRow + " <button class='btn btn-sm btn-success btn-save'> Save</button>";
emptyNewRow = emptyNewRow + " <button class='btn btn-sm btn-success btn-cancel'> Delete</button>";
emptyNewRow = emptyNewRow + " </td>";
emptyNewRow = emptyNewRow + "</tr>";
var rowButtons ="<button class='btn btn-success btn-sm btn-edit' > Edit </button> <button class='btn btn-danger btn-sm' > Delete </button>";
var rowUpdateButtons ="<button class='btn btn-success btn-sm btn-save' > Update </button> <button class='btn btn-danger btn-sm btn-save' > Delete </button> ";
$(document).ready(function () {
//debugger;
$("#tblData tbody").append(emptyRow); // adding empty row on page load
$("#btnAdd").click(function () {
//debugger;
if ($("#tblData tbody").children().children().length == 1) {
$("#tblData tbody").html("");
}
//debugger;
$("#tblData tbody").append(emptyNewRow); // appending dynamic string to table tbody
});
$('#tblData').on('click', '.btn-save', function () {
const id = $(this).parent().parent().find(".txtID").val();
$(this).parent().parent().find(".tdID").html(""+id+"");
const name = $(this).parent().parent().find(".txtName").val();
$(this).parent().parent().find(".tdName").html(""+name+"");
const address = $(this).parent().parent().find(".txtAddress").val();
$(this).parent().parent().find(".tdAddress").html(""+address+"");
const age = $(this).parent().parent().find(".txtAge").val();
$(this).parent().parent().find(".tdAge").html(""+age+"");
$(this).parent().parent().find(".tdAction").html(rowButtons);
});
$('#tblData').on('click', '.btn-danger', function () { // registering function for delete button
$(this).parent().parent().remove();
if ($("#tblData tbody").children().children().length == 0) {
$("#tblData tbody").append(emptyRow);
}
});
$('#tblData').on('click', '.btn-cancel', function () {
$(this).parent().parent().remove();
});
$('#tblData').on('click', '.btn-edit', function () {
const id =$(this).parent().parent().find(".tdID").html();
$(this).parent().parent().find(".tdID").html("<input type='text' value='"+id+"' class='form-control txtID' />");
const name =$(this).parent().parent().find(".tdName").html();
$(this).parent().parent().find(".tdName").html("<input type='text' value='"+name+"' class='form-control txtName' />");
const address =$(this).parent().parent().find(".tdAddress").html();
$(this).parent().parent().find(".tdAddress").html("<input type='text' value='"+address+"' class='form-control txtAddress' />");
const age =$(this).parent().parent().find(".tdAge").html();
$(this).parent().parent().find(".tdAge").html("<input type='text' value='"+age+"' class='form-control txtAge' />");
$(this).parent().parent().find(".tdAction").html(rowUpdateButtons);
});
$('.btn-save').click(function() {
localStorage.setItem('txtId', id);
localStorage.getItem('txtId');
localStorage.setItem('txtName', name);
localStorage.getItem('txtName');
localStorage.setItem('txtAddress', address);
localStorage.getItem('txtAddress');
localStorage.setItem('txtAge', age);
localStorage.getItem('txtAge');
});
$('.btn-danger').click(function() {
localStorage.removeItem('txtID');
localStorage.removeItem('txtName');
localStorage.removeItem('txtAddress');
localStorage.removeItem('txtAge');
});
});
</script>
</body>
</html>
Consider the following jsFiddle Example. I used jsFiddle as it allows for the use of localStorage where Stack Overflow Snippets do not.
Fiddle: https://jsfiddle.net/Twisty/3u6gpc49/
JavaScript
$(function() {
var myEmptyRow = [{
class: "tdID",
content: $("<input>", {
type: "text",
class: "form-control txtID"
})
}, {
class: "tdName",
content: $("<input>", {
type: "text",
class: "form-control txtName"
})
}, {
class: "tdAddress",
content: $("<input>", {
type: "text",
class: "form-control txtAddress"
})
}, {
class: "tdAge",
content: $("<input>", {
type: "text",
class: "form-control txtAge"
})
}, {
class: "tdAction",
content: [
$("<button>", {
class: "btn btn-sm btn-success btn-save"
}).html("Save"),
$("<button>", {
class: "btn btn-sm btn-success btn-cancel"
}).html("Delete")
]
}];
var myButtons = {
edit: [
$("<button>", {
class: "btn btn-success btn-sm btn-edit"
}).html("Edit"),
$("<button>", {
class: "btn btn-danger btn-sm"
}).html("Delete")
],
update: [
$("<button>", {
class: "btn btn-success btn-sm btn-save"
}).html("Update"),
$("<button>", {
class: "btn btn-danger btn-sm"
}).html("Delete")
]
};
function getStore(index) {
console.log("Get data for " + index);
return JSON.parse(localStorage.getItem(index));
}
function saveStore(index, data) {
console.log("Saving Data to " + index, data);
localStorage.setItem(index, JSON.stringify(data));
}
function deleteStore(index) {
console.log("Deleting Data for " + index);
localStorage.removeItem(index);
}
function addRow(target, data, empty) {
if (target == undefined) {
target = $("table:eq(0)");
}
if (empty == undefined) {
empty = false;
}
if (data == null) {
return false;
}
console.log("Add Row to " + target.attr("id"), empty);
if (empty) {
$("tbody", target).html("");
}
var row = $("<tr>").appendTo($("tbody", target));
if (data == undefined) {
// Add Empty Row
$("<td>", {
colspan: 4,
class: "text-center"
}).appendTo(row);
} else {
row.addClass("trNewRow");
$.each(data, function(i, cell) {
$("<td>", {
class: cell.class
}).append(cell.content).appendTo(row);
});
}
console.log(data, data.length);
if (data.length == 4) {
$("<td>", {
class: "tdAction"
}).append(myButtons.edit).appendTo(row);
}
return row;
}
function saveRow(row) {
if (row == undefined) {
return false;
}
var rowData = [{
class: "tdID",
content: $(".txtID", row).val()
},
{
class: "tdName",
content: $(".txtName", row).val()
}, {
class: "tdAddress",
content: $(".txtAddress", row).val()
}, {
class: "tdAge",
content: $(".txtAge", row).val()
}
];
$.each(rowData, function(i, c) {
$("." + c.class, row).html(c.content);
});
$(".tdAction", row).html(myButtons.edit);
saveStore("row-" + row.index(), rowData);
}
function init() {
if (localStorage.length == 0) {
addRow($("#tblData"));
} else {
console.log("Found Local Storage. Rows: " + localStorage.length);
$.each(localStorage, function(k, o) {
var rowData = getStore(k);
console.log(k, rowData);
addRow($("#tblData"), rowData);
});
}
}
init();
$("#btnAdd").click(function() {
addRow($("#tblData"), myEmptyRow, $("#tblData tbody tr td").length == 1 ? true : false);
});
$('#tblData').on('click', '.btn-save', function() {
saveRow($(this).closest("tr"));
});
$('#tblData').on('click', '.btn-danger, .btn-cancel', function() {
// registering function for delete button
deleteStore("row-" + $(this).closest("tr").index());
$(this).closest("tr").remove();
if ($("#tblData tbody tr").length == 0) {
addRow($("#tblData "));
}
});
$('#tblData').on('click', '.btn-edit', function() {
var row = $(this).closest("tr");
$(".tdID", row).html("<input type='text' value='" + $(".tdID", row).html() + "' class='form-control txtID' />");
$(".tdName", row).html("<input type='text' value='" + $(".tdName", row).html() + "' class='form-control txtName' />");
$(".tdAddress", row).html("<input type='text' value='" + $(".tdAddress", row).html() + "' class='form-control txtAddress' />");
$(".tdAge", row).html("<input type='text' value='" + $(".tdAge", row).html() + "' class='form-control txtAge' />");
$(".tdAction", row).html(myButtons.update);
});
});
There is a lot to break down here. I will try to focus on the Save, Edit, and Delete buttons. To help with this, it is best to create functions for these operations. Also, you must remember that localStorage can only contain String data.
We will start with Saving a Row. We gather all the details for the Row and then pass them to the saveStore() function. This takes two parameters, an index and the data.
function saveStore(index, data) {
console.log("Saving Data to " + index, data);
localStorage.setItem(index, JSON.stringify(data));
}
As we're passing in an Array of Objects, and not a String, we must convert this to a String. I use JSON.stringify() to accomplish this. This results in a JSON String that can be parsed later.
If we are Deleting a row, we can do this.
function deleteStore(index) {
console.log("Deleting Data for " + index);
localStorage.removeItem(index);
}
I am using the format row-0, row-1, row-2... for the indexes.
If rows are saved and the browser crashes or the user reloads the page for some reason, you might want to display the currently saved Rows. this is where our final function comes in handy.
function getStore(index) {
console.log("Get data for " + index);
return JSON.parse(localStorage.getItem(index));
}
Here we can collect the saved Row data and parse it back into an Array of Objects. Often times, we will know the index name. When we load the page, we may not know the names or how many rows are saved. We can treat localStorage similar to an Object to check on this.
$.each(localStorage, function(k, o) {
var rowData = getStore(k);
console.log(k, rowData);
addRow($("#tblData"), rowData);
});
This iterates over each of the localStore items and gets the index name.
there are a lot of other parts to this that I updated to jQuery. I used what is considered best practices. That might be a matter of opinion, and you can choose to setup your code any way you like. To address this question, please focus on the functions created to help with localStorage.
In regards to your selectors, using .children(), this is not a good method. Consider that $("tr").find(".tdID") is the same as $(".tdID", "tr")
Selector context is implemented with the .find() method; therefore, $( "li.item-ii" ).find( "li" ) is equivalent to $( "li", "li.item-ii" ).
This means that if you can target the parent Row, you can more easily select child elements. Example: $(".tdID", row).html()
localStorage.setItem() does exactly what it suggests... It sets that value to that key in local storage. If any previous value was set, it overwrites that value.
If you want to append to the previous value in some way, you need to read that value, update it, and write it back. For example, this would append the value as an array element:
let txtId = localStorage.getItem('txtId') || [];
txtId.push(id);
localStorage.setItem('txtId', txtId);
(Make sure to clear existing values before debugging this.)
The idea above is to read the stored value, which should be an array if it was previously set. If no value exists, default to an empty array. Then append the new id value to that array. Then write that array back to local storage.
Basically, local storage won't organize your data for you. It will store whatever you write to it and only what you write to it. It's up to you to manage how that data is organized and what you're writing to it.
I have this in JS and the code below. I want to send the data-id into modal and also when closing the modal to dismiss the data-id. how can I do that using javaScript???
fetch("https://data.uk/api/" + $searchValue).then(
res => {
res.json().then(
data => {
if (data.length > 0) {
var temp = "";
temp += "<thead>";
temp += "<tr>";
temp += "<th>ID</th>";
temp += "<th>Force Name</th>";
temp += "<th>Details</th>";
temp += "</tr>";
temp += "</thead>";
temp += "<tbody>";
data.forEach((itemData) => {
temp += "<tr><td>" + itemData.id + "</td>";
temp += "<td>" + itemData.name + "</td>";
temp += "<td><a href='#' data-id='" + itemData.id + "' data-toggle='modal' data-target='#myModal'>More Detail</a></td></tr>";
});
temp += "</tbody>";
document.getElementById('data').innerHTML = temp;
}
}
)
}
)
and I want to get each data-id value into modal using this
$("myModal").on("show.bs.modal", function(e) {
var b = $(e.relatedTarget);
var r = b.data("id");
var modal = $(this);
modal.find("#me").text(r);
})
and this is my modal, I want when I open the modal to be able to capture the data-id and display it in id="me"
<div class="modal-body" id="modal-body">
<div class="row m-0">
<div class="col-4">
People name & twitter
</div>
<div class="col-8">
Descriptions
<h2 id="me"></h2>
</div>
</div>
</div>
You can access data-... attribute with dataset property, e.g. given
<div id="my-element" data-id="myData"></div>
you can get it with
document.getElementById("my-element").dataset.id
I have create a function that adds rows based on value of a dropdown list.
The user selects a project, clicks the Add button, and a row with the name of the project and a set of cells are added to the table.
The name of the project is inside a 'th' tag.
I want to add a condition that the add button does not add a row if the project has already been added:
<script>
$(document).ready(function() {
var i = 1
var tbody = $('#myTable').children('tbody');
//Then if no tbody just select your table
var table = tbody.length ? tbody : $('#myTable');
/* table.find('th').each(function(){
if (th.value = projval)
alert("project already in");
});*/
$('#addrow').click(function() {
//Add row
var projval = $('#projSel').val();
$('#myTable > tbody > tr > th').each(function(index, th) {
console.log(index);
// if($("th").eq(index).attr('id') = projval) {
// alert("Exist");
// }
});
table.append('<tr><th scope="row" id="' + projval + '">' + projval + '</th>\
<td><input class="form-control" type="text" id="inMon' + i + '" placeholder="00:00"></td>\
<td><input class="form-control" type="text" id="inTue' + i + '" placeholder="00:00"></td>\
<td><input class="form-control" type="text" id="inWed' + i + '" placeholder="00:00"></td>\
<td><input class="form-control" type="text" id="inThu' + i + '" placeholder="00:00"></td>\
<td><input class="form-control" type="text" id="inFri' + i + '" placeholder="00:00"></td>\
<td><input class="form-control" type="text" id="inSat' + i + '" placeholder="00:00"></td>\
<td><input class="form-control" type="text" id="inSun' + i + '" placeholder="00:00"></td>\
<td><button name="remove" id="' + i + '" class="btn btn-danger btn_remove btn-sm" onclick="deleteRow(this)">X</td></tr>');
i++;
})
});
projVal variable is the value selected from the dropdown list
myTable is the ID of the table.
I cannot figure how to write the if condition so that the index retrieves the value of 'th' ID and compares it to the already exisiting 'th' added by user.
Check with the below code:
$('#addrow').click(function () {
var projval = $('#projSel').val();
var projectAdded = $('tr>th[scope=row][id="' + projval + '"]', table).length > 0;
if (projectAdded) {
alert('project already in');
return false;
}
// ... Add Row Code
i++;
})
help please
I just learned codeigniter, I have a problem when inserting data.
I want to input or insert data that is looking for from the database, for example can be seen in the picture.
when I insert it into the database, the error message is the data that I inserted NULL
Search by kode
{
"result":
[
{
"id_runsheet":"6",
"kd_runsheet":"RUNSHEET-0000-0003",
"reciver_name":"arif",
"tracking_number":"RJC-0000-0003",
"status":"Consignee Unknown",
"id_runsheet_detail":"6",
"id_outdes":"3"
},
{
"id_runsheet":"6",
"kd_runsheet":"RUNSHEET-0000-0003",
"reciver_name":"hendra",
"tracking_number":"RJC-0000-0004",
"status":"Closed",
"id_runsheet_detail":"6",
"id_outdes":"3"
}
]
}
Controller
public function cari(){
$id=$_POST['kd_runsheet'];
$data['result']=$this->M_inbound_undel->caridb($id);
echo json_encode($data);
}
Model
public function save(){
$data = array(
'id_runsheet' => $this->input->post('id_runsheet'),
'id_runsheet_detail' => $this->input->post('id_runsheet_detail'),
'id_outdes' => $this->input->post('id_outdes')
);
$this->M_inbound_undel->db_save($data);
echo $this->session->set_flashdata('message','success');
redirect('backend/inbound_undel');
}
View
<form class="form-signin" method="post" action="<?php echo base_url().'backend/inbound_undel/save';?>">
<div class="box">
<div class="box-header">
<div class="row">
<div class="form-group col-md-2">
<label for="field-1" class="control-label">Tanggal</label>
<input name="" value="<?php echo(date('Y-m-d H:i:s')) ?>" class="form-control" type="text" placeholder="" readonly required="">
</div>
<div class="form-group col-md-4">
<label for="field-1" class="control-label">KODE RUNSHEET</label>
<input name="kd_runsheet" class="form-control" id="kode" type="text" placeholder="Masukan Kode Runsheet" style="" required="">
<span style="font-size:11px; color:#00a65a;">No resi hanya bisa tampil apabila resi sudah di Inbound</span>
</div>
</div>
</div>
</div>
<div class="box">
<div class="box-body">
<table id="databel" class="table table-bordered table-striped" style="width: 100%; cellspacing: 0;">
<thead>
<tr>
<th>Kode Runsheet</th>
<th>Kode Resi</th>
<th>Penerima</th>
<th>status terakhir</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
<div class="box-footer">
<button type="submit" class="btn bg-orange btn-flat margin">Simpan</button>
</div>
</div>
</div>
</form>
AJAX
$(document).ready(function(){
$('#kode').on('input',function(){
var kode=$(this).val(); //serach by kode
$.ajax({
url : "<?php echo base_url('backend/inbound_undel/cari')?>",
type: 'POST',
dataType: 'JSON',
data : {kd_runsheet: kode},
success:function (data) {
//result
var result = data.result;''
var row = "";
for(i=0; i < result.length; i++) {
row += "<tr>";
row += "<td>"+result[i].kd_runsheet+"</td>";
row += "<td>"+result[i].tracking_number+"</td>";
row += "<td>"+result[i].reciver_name+"</td>";
row += "<td class='label bg-red'>"+result[i].status+"</td>";
row += "</tr>";
}
$('#tbody').html(row);
}
});
event.preventDefault();
});
});
when I insert it into the database, the error message is the data that I insert all NULL
It happens because your save() model expected 3 post parameters to be received, yet none of them are present.
After looking at the returned json data that you've provided, you could make a hidden input for each of the required save() parameters :
<script>
$(document).ready(function() {
$('#kode').on('input', function() {
var kode = $(this).val(); //serach by kode
$.ajax({
url: "<?php echo base_url('backend/inbound_undel/cari') ?>",
type: 'POST',
dataType: 'JSON',
data: {
kd_runsheet: kode
},
success: function(data) {
//result
var result = data.result;
var row = "";
for (i = 0; i < result.length; i++) {
row += "<tr>";
row += "<td>" + result[i].kd_runsheet + "</td>";
row += "<td>" + result[i].tracking_number + "</td>";
row += "<td>" + result[i].reciver_name + "</td>";
row += "<td class='label bg-red'>" + result[i].status + "</td>";
row += "</tr>";
}
$('#tbody').html(row);
// begin appended hidden inputs
let input = "";
for (i = 0; i < result.length; i++) {
input += "<input type='hidden' name='id_runsheet' value='" + result[i].id_runsheet + "' />";
input += "<input type='hidden' name='id_runsheet_detail' value='" + result[i].id_runsheet_detail + "' />";
input += "<input type='hidden' name='id_outdes' value='" + result[i].id_outdes + "' />";
}
$('#databel').html(input);
// end appended hidden inputs
}
});
event.preventDefault();
});
});
</script>
I'm creating a website with razor with a database but I have a problem changing database elements from within the webpage.
All elements are shown in a table with an update button. If the button is clicked, it sends it's ID to a JavaScript function. In that function an array is created with all the necessary properties. Then I want to pass that array to my razor function, but when calling the function in JavaScript, I get an error (The name 'kamer' does not exist in the current context). Anyone knows a solution?
thanks!
my razor function:
#functions{
public String saveRoom(string[] room){
var db = Database.Open("Studentenkamers");
var sql = "UPDATE Studentkamer SET oppervlakte='" + room[1] + "', locatie='" + room[2] + "', type='" + room[3] + "', vrij='" + room[4] + "' WHERE id='" + room[0] + "'";
db.Query(sql);
return "ok";
}
}
the html and javascript code:
#foreach(var row in db.Query(getKamers))
{
<tr id="#row.id">
<td class="td-id">#row.id</td>
<td class="td-opp"><input type="text" value="#row.oppervlakte" name="oppervlakte" id="td-opp" /></td>
<td class="td-loc">#row.locatie</td>
<td class="td-type"><input type="text" value="#row.type" name="type" id="td-type" /></td>
<td class="td-kamernr">#row.kamernr</td>
<td class="td-vrij"><input type="text" value="#row.vrij" name="vrij" id="td-vrij" /></td>
<td class="td-update"><input type="button" value="opslaan" onclick="updateRoom(this.id)" name="opslaan" id="#row.id" /></td>
</tr>
}
</table>
<script type="text/javascript">
function updateRoom(id) {
var opp = $("#" + id + " .td-opp input").attr("value");
var locatie = $("#" + id + " .td-loc").html();
var type = $("#" + id + " .td-type input").attr("value");
var kamernr = $("#" + id + " .td-kamernr").html();
var vrij = $("#" + id + " .td-vrij input").attr("value");
var kamer = [id, opp, locatie, type, kamernr, vrij];
alert(kamer);
#saveRoom(kamer);
}
</script>