Delete an item in array which is stored in localStorage - javascript

Im display some data into table and for each row there is Delete button, when button clicked it should Delete item in array which is stored in localStorage by passing id and than Assign it back to LocalStorage.
HTML:
<table>
<tbody id="ResultProduct">
<tr class="RMAJS">
<td><input type="text" id="item1" name="itemName" value="Computer" /></td>
<td><a data-localstorage-id='ae90ac1a-64c4-49a7-b588-ae6b69a37d47' class="deletebtn">Delete</a></td>
</tr>
<tr class="RMAJS">
<td><input type="text" id="item2" name="itemName" value="Mobile" /></td>
<td><a data-localstorage-id='6b1ccc7e-322c-4f5f-81f9-b1fd68c0eb8b' class="deletebtn">Delete</a></td>
</tr>
</tbody>
</table>
LocalStorage :
["ae90ac1a-64c4-49a7-b588-ae6b69a37d47","6b1ccc7e-322c-4f5f-81f9-b1fd68c0eb8b"]
0: "ae90ac1a-64c4-49a7-b588-ae6b69a37d47"
1: "6b1ccc7e-322c-4f5f-81f9-b1fd68c0eb8b"
JavaScript :
$('#ResultProduct').on('click', '.deletebtn', function (e) {
var targetElement = $(e.target);
var getID = $(targetElement).attr("data-localstorage-id");
var getLocalStorage = JSON.parse(localStorage.getItem("users"));
for (var i = 0; i < getLocalStorage.length; i++) {
var Val = getLocalStorage[i]
//Here is my problem for example i want to delete this item
//"6b1ccc7e-322c-4f5f-81f9-b1fd68c0eb8b" from array
//How can i do that ??
localStorage.setItem('users', JSON.stringify(??)); //Assign it back to LocalStorage.
}
$(targetElement).closest("tr.RMAJS").remove();
})

$('#ResultProduct').on('click', '.deletebtn', function (e) {
var targetElement = $(e.target);
var getID = $(targetElement).attr("data-localstorage-id");
var getLocalStorage = JSON.parse(localStorage.getItem('users'));
getLocalStorage = getLocalStorage.filter(e => e !== getID);
localStorage.setItem('users', JSON.stringify(getLocalStorage));
$(targetElement).closest("tr.RMAJS").remove();
});

Related

Remove first duplicate from an array of objects in JavaScript

On input change I create an array of objects. When any value enter within the input field, it pushes objects into array but the problem is when a text field is updated, it does again push items into array. I need to update the array instead of pushing more items.
var tableData = [];
$('.aantalNumber').change(function(){
var aantalNumberVal = $(this).val()
var Productnummer = $(this).closest('tr').find('.product_number').text();
var Productnaam = $(this).closest('tr').find('.product_name').text();
var verpakking =$(this).closest('tr').find('.verpakking').text();
tableData.push({aantalNumber:aantalNumberVal,Productnummer:Productnummer,Productnaam:Productnaam,verpakking:verpakking });
console.log(tableData);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<tr>
<td><input type="number" class="aantalNumber" name="Aantal1"></td>
<td class="product_number">01454</td>
<td class="product_name">Vendor Handdoeken ZZ vouw</td>
<td class="verpakking">5000 velper verpakking</td>
</tr>
<tr>
<td><input type="number" class="aantalNumber" name="Aantal2"></td>
<td class="product_number">218031</td>
<td class="product_name">Vendor Handdoeken ZZ vouw</td>
<td class="verpakking">5000 velper verpakking</td>
</tr>
<!-- Repeated tr and so on -->
First check if value exist, if available then update else push into tableData
var tableData = [];
$('.aantalNumber').change(function() {
var aantalNumberVal = $(this).val()
var Productnummer = $(this).closest('tr').find('.product_number').text();
var Productnaam = $(this).closest('tr').find('.product_name').text();
var verpakking = $(this).closest('tr').find('.verpakking').text();
if (tableData.some(tableData => tableData.Productnummer === Productnummer)) {
updateTableData(Productnummer, aantalNumberVal);
} else {
tableData.push({
aantalNumber: aantalNumberVal,
Productnummer: Productnummer,
Productnaam: Productnaam,
verpakking: verpakking
});
}
console.log(tableData);
});
function updateTableData(value, aantalNumber) {
for (var i in tableData) {
if (tableData[i].Productnummer == value) {
tableData[i].aantalNumber = aantalNumber;
break; //Stop this loop, we found it!
}
}
}
Working Demo

How to reference a element within a table

I am need of help. I am trying to figure out the below:
<script>
var ct = 1;
function new_bank()
{
ct++;
var div1 = document.createElement('div');
div1.id = ct;
// bank to delete extended form elements
var delLink = 'delete';
div1.innerHTML =
document.getElementById("newbanktpl").innerHTML + delLink;
document.getElementById('newbank').appendChild(div1);
}
// function to delete the newly added set of elements
function delIt(eleId)
{
d = document;
var ele = d.getElementById(eleId);
var parentEle = d.getElementById('newbank');
parentEle.removeChild(ele);
findTotalA();
}
</script>
<!-- Template -->
<div id="newbanktpl">
<table>
<tr>
<td></td>
<td><textarea name="BankAccount[]"></textarea></td>
<td><input type="number" onblur="findTotalA()" name="Value[]"/></td>
<td><input type="number" name="Ownership[]" /></td>
<td>**ADD DELETED LINK HERE** </td>
</tr>
</table>
what I am after is the delete function to be within the table - at the moment the delete function is after the newbanktpl, and I want in within... on the last ADD DELETED LINK HERE.
give the link in the template a class
clone the template
update the div's ID
assign the delIt function to the onclick of the link
give the link a data-delete attribute that references the ID to delete.
insert the clone after the last bank that was inserted
assign the clone as the new "last bank"
var ct = 1;
var tmpl = document.getElementById("newbanktpl");
var lastBank = tmpl;
function new_bank() {
var clone = tmpl.cloneNode(true);
clone.id = "bank_" + ct;
ct++;
var delLink = clone.querySelector(".delete_link");
delLink.setAttribute("data-delete", clone.id);
delLink.onclick = delIt;
lastBank.parentNode.insertBefore(clone, lastBank.nextSibling);
lastBank = clone;
}
// function to delete the newly added set of elements
function delIt() {
var id = this.getAttribute("data-delete");
var ele = document.getElementById(id);
if (ele === lastBank) {
lastBank = ele.previousElementSibling;
}
ele.parentNode.removeChild(ele);
// findTotalA();
}
#newbanktpl {
display: none;
}
<!-- Template -->
<div id="newbanktpl">
<table>
<tr>
<td></td>
<td><textarea name="BankAccount[]"></textarea></td>
<td><input type="number" onblur="findTotalA()" name="Value[]" /></td>
<td><input type="number" name="Ownership[]" /></td>
<td><a class="delete_link" href="#">delete</a></td>
</tr>
</table>
</div>
<button onclick="new_bank()">New Bank</button>
Try adding an id to your td, then you can use it in JS.
In your HTML
<table>
<tr>
...
<td>delete</td>
</tr>
</table>
In your script tag
...
document.getElementById("delete").href="javascript:delIt('+ ct +')";
...
The Entire function should look like this:
var ct = 1;
function new_bank() {
ct++;
var div1 = document.createElement('div');
div1.id = ct;
document.getElementById("delete").href="javascript:delIt('+ ct +')";
document.getElementById('newbank').appendChild(div1);
}
P.S. I don't know why you are trying to save bytes from the computer by calling variables with such short names, it's a waist of your time, it won't make any difference to the computer, but it makes it harder to understand your code.

Select and change input value in table using data-attribute and JavaScript

I have a table with input fields, and I would like to fill this fields with some data, that users can change if they like.
//Server side processing gives me an array like:
var data = [];
data.push({"calcname" : "calc1", "value" : 5});
data.push({"calcname" : "calc2", "value" : 10});
//The data array may not have data for all the rows, and the order of items may not be the same.
//For each data item, I select the appropriate row:
for (var i = 0; i < data.length; i++) {
var myRow = $('[data-calcname="' + data.calcname + '"]')[0];
//And now, try to select the input in each row, but I can't get it to work..:
//var myInput = myRow.find("input:text")
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr data-calcname="calc1">
<td>
SomeName
</td>
<td>
SomeDescription
</td>
<td>
<input type="text">
</td>
</tr>
<tr data-calcname="calc2">
<td>
SomeName
</td>
<td>
SomeDescription
</td>
<td>
<input type="text">
</td>
</tr>
</table>
However, I have trouble selecting the various input fields, in order to fill them out, as shown in the snippet.
I guess there is an easy jQuery syntax to do this, but despite my best efforts, I have not been able to find it.
How can I achieve this?
You can, in a cleaner way, iterate over the data array with Array.prototype.forEach() and execute a provided function once for each array el element.
The rest is jQuery.
Code:
//Server side processing gives me an array like:
var data = [];
data.push({"calcname" : "calc1", "value" : 5});
data.push({"calcname" : "calc2", "value" : 10});
data.forEach(function(el) {
$('tr[data-calcname="' + el.calcname + '"]').find('input:text').val(el.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr data-calcname="calc1">
<td>
SomeName
</td>
<td>
SomeDescription
</td>
<td>
<input type="text">
</td>
</tr>
<tr data-calcname="calc2">
<td>
SomeName
</td>
<td>
SomeDescription
</td>
<td>
<input type="text">
</td>
</tr>
</table>
//Server side processing gives me an array like:
var data = [];
data.push({"calcname" : "calc1", "value" : 5});
data.push({"calcname" : "calc2", "value" : 10});
//The data array may not have data for all the rows, and the order of items may not be the same.
//For each data item, I select the appropriate row:
for (var i = 0; i < data.length; i++) {
var myRow = $('[data-calcname="' + data[i].calcname + '"]').find("input").val(data[i].value);
//And now, try to select the input in each row, but I can't get it to work..:
//var myInput = myRow.find("input:text")
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr data-calcname="calc1">
<td>
SomeName
</td>
<td>
SomeDescription
</td>
<td>
<input type="text">
</td>
</tr>
<tr data-calcname="calc2">
<td>
SomeName
</td>
<td>
SomeDescription
</td>
<td>
<input type="text">
</td>
</tr>
</table>
Use attribute selector to select the td. By combining with data[i].calcname to get the desired, with .find() to get the input.
Set the value using .val()
You need to write you selector of the tr like this var myRow = $('tr[data-calcname="' + data[i].calcname + '"]')
In your case data[i] would be: data[0] = ({"calcname" : "calc1", "value" : 5}) data[1] = ({"calcname" : "calc2", "value" : 10})
//Server side processing gives me an array like:
var data = [];
data.push({"calcname" : "calc1", "value" : 5});
data.push({"calcname" : "calc2", "value" : 10});
//The data array may not have data for all the rows, and the order of items may not be the same.
//For each data item, I select the appropriate row:
for (var i = 0; i < data.length; i++) {
var myRow = $('tr[data-calcname="' + data[i].calcname + '"]');
var myInput = myRow.find("input:text").val(data[i].value);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr data-calcname="calc1">
<td>
SomeName
</td>
<td>
SomeDescription
</td>
<td>
<input type="text">
</td>
</tr>
<tr data-calcname="calc2">
<td>
SomeName
</td>
<td>
SomeDescription
</td>
<td>
<input type="text">
</td>
</tr>
</table>
As data is an array i.e. data[i], use index to access the elements, also there is no need use [0] which returns the reference to DOM element.
var data = [];
data.push({"calcname" : "calc1", "value" : 5});
data.push({"calcname" : "calc2", "value" : 10});
for (var i = 0; i < data.length; i++) {
var myRow = $('[data-calcname="' + data[i].calcname + '"]');
var myInput = myRow.find("input:text");
myInput.val(data[i].value)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr data-calcname="calc1">
<td>
SomeName
</td>
<td>
SomeDescription
</td>
<td>
<input type="text">
</td>
</tr>
<tr data-calcname="calc2">
<td>
SomeName
</td>
<td>
SomeDescription
</td>
<td>
<input type="text">
</td>
</tr>
</table>
You set up a for loop correctly but now you need to use your index i to access the desired element in your array data: data[i].calcname
You don't need to get the row but you need to get the input inside that row: $('[data-calcname="' + data[i].calcname + '"] td input')
You change a textfield's title by setting its value property: myInput.value = "new value"
//Server side processing gives me an array like:
var data = [];
data.push({"calcname" : "calc1", "value" : 5});
data.push({"calcname" : "calc2", "value" : 10});
//The data array may not have data for all the rows, and the order of items may not be the same.
//For each data item, I select the appropriate row:
for (var i = 0; i < data.length; i++) {
var myInput = $('[data-calcname="' + data[i].calcname + '"] td input')[0];
myInput.value = data[i].value
}
The for of loop
If you don't understand step 1. Maybe it is simpler to use the for of loop:
for (let element of data) {
var myInput = $('[data-calcname="' + element.calcname + '"] td input')[0];
myInput.value = element.value
}

jquery efficient way to select tablerow data

I have a table with multiple rows of the same pattern:
<tr role="row" class="even">
<td><input type="checkbox" id="valj4"></td>
<td>Generell grupp</td>
<td>IKT Ipad11- Mirko</td>
<td>Grundinställningar</td>
</tr>
Each row has a checkbox with unique ID, what would be the most efficient way to get a list of UUIDs for the rows with a checked checkbox. I would like to use jQuery.
$(function() {
var texts = [];
$('tr td:has(input:checkbox:checked) ~ td > a').each(function(i, e) {
texts.push($(e).attr('href'));
});
$('#result').html(texts.join('<br/>'));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr role="row" class="even">
<td>
<input type="checkbox" id="valj4" checked>
</td>
<td>Generell grupp</td>
<td>IKT Ipad11- Mirko (...5)
</td>
<td>Grundinställningar</td>
</tr>
<tr role="row" class="even">
<td>
<input type="checkbox" id="valj4">
</td>
<td>Generell grupp</td>
<td>IKT Ipad11- Mirko (...6)
</td>
<td>Grundinställningar</td>
</tr>
<tr role="row" class="even">
<td>
<input type="checkbox" id="valj4" checked>
</td>
<td>Generell grupp</td>
<td>IKT Ipad11- Mirko (...7)
</td>
<td>Grundinställningar</td>
</tr>
</table>
<div id="result"/>
Getting the UUID is then an easy exercise in string chopping.
I assume your table has an id and it's "#table-id":
$("#table-id").find(":checked")
would get you all the checked checkboxes and radio boxes.
$("#table-id").find("input[type='checkbox']:checked")
would get you all the checked checkboxes.
var ids = "";
$("#table-id").find("input[type='checkbox']:checked").each(function(){
ids += $(this).attr("id") + ",";
});
would give you a comma seperated list containing the ids of checked checkboxes in the table.
and the UUIDS list:
var UUIDs = "";
$("#table-id").find("input[type='checkbox']:checked").each(function(){
var href = $(this).closest("tr").find("td > a").first().attr("href");
var UUID = href.split('?')[1];
UUIDS += UUID + ",";
});
I would try the following
var ids = [];
$("#table input:checkbox:checked").each(function () {
var uuid = getParameter($(this).closest('tr').find('a').eq(0).attr('href'))
ids.push(uuid);
});
function getParameter(url) {
var regex = new RegExp("[\\?&]uuid=([^&#]*)"),
results = regex.exec(url);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
where #table is the id of your table
Example
jQuery('#formId').find('tr[class=even]').each(function () {
var rowId = "";
this.find('input[type=checkbox]').each(function() {
if(this.checked) {
rowId = "row" + $(this).val();
}
});
$(this).attr('id', rowId);
});
Create a new list of UUIDs.
var listOfUUIDs = [];
Get the checked input, go up to grandparent (the tr), then find the a inside it.
Go through the list of a's, adding UUIDs to the list.
$("tr input[checked=checked]").parent().parent().find("td a").each(function(){
listOfUUIDs.push(
$(this).prop('href').substr(indexOf("uuid=") + 5)
)
});
This should give you what you need.
$('tr').each(function(index) {
var $this = $(this),
input = $this.find('input'),
result = '';
if ( input.is(':checked') ) {
var uuid = $this.find('a').attr('href').replace(/^\/Home\/DeviceDetails\?uuid=/g, ""),
result = result + index + '. ' + input.attr('id') + ' has the uuid: ' + uuid + '<br />';
}
$('#result').html(result);
});
try this
$( "input[type=checkbox]" ).change(function() {
if($(this).is(":checked")) {
alert($(this).attr("id"));
}
});

Javascript for each instead of multiple if

Please, give "direction where to go"
Many input rows. For each row is field class="row_changed"
If value in the field is higher than 0, then ajax pass entire row to php. Each row is included in <tr> </tr> For each <tr> id is set <tr id='row'>
At the moment I can do it only with many if
Need something like: if value in any of field field class="row_changed" is more than 0, then pass corresponding row (inside <tr id='row'>) to php.
Here is some information. Is it suitable for the described case?
<tr id='row1'>
<td>
<input type="text" name="row1[]" id="date_day1" class="row_changed1">
</td>
...
<td>
<input type="text" name="row1[]" id="is_row_changed1" size="1">
<script>
$(".row_changed1").on("change", function () {
document.getElementById('is_row_changed1').value = 1;
});
</script>
</td>
<tr>
if ($("#is_row_changed1").val() > 0) {
$.post("_autosave_array.php", $("#row1 :input").serialize(), function (data1) {
$('#load1').html(data1);
$('#is_row_changed1').val(0)
});
var str = $("#row1 :input").serialize();
$("#load1_1").text(str);
}
if ($("#is_row_changed2").val() > 0) {
$.post("_autosave_array.php", $("#row2 :input").serialize(), function (data2) {
$('#load2').html(data2);
$('#is_row_changed2').val(0)
});
var str = $("#row2 :input").serialize();
$("#load2_1").text(str);
}
Something like this should do it:
function doPost(changedRowId,serializeRowId,resultId,serializeResultId){
if ($(changedRowId).val() > 0) {
$.post("_autosave_array.php", $(serializeRowId + ":input").serialize(), function (data2) {
$(resultId).html(data2);
$(changedRowId).val(0)
});
var str = $("#row2 :input").serialize();
$(serializeResultId).text(str);
}
var rowData = [{changedRowId: "#is_row_changed1", serializeRowId: "#row1", resultId: "#load1", serializeResultId: "#load1_1"},
{changedRowId: "#is_row_changed2", serializeRowId: "#row2 ", resultId: "#load2". serializeResultId: "#load2_1"}
];
for(var i = 0; i < rowData.length; ++i){
var data = rowData[i];
doPost(data.changedRowId,data.serializeRowId,data.resultId,data.serializeResultId);
}
I can see that all your input tags have the same name, you can select all of them by name then put your condition/logic inside
sample:
$("input[name='row1[]']").each(function(){
if($(this).val()>0){
$.post("_autosave_array.php", $("#row1 :input").serialize(), function (data1) {
$('#load1').html(data1);
$('#is_row_changed1').val(0)
}
});

Categories