How to delete object in array using localstorage? - javascript

I have to delete object in array and it should be deleted from localstorage. I am trying to delete it by using splice method but not actually getting how to use it.
Folloeing is my code which i have tried-
var details = [];
function addEntry() {
var existingEntries = JSON.parse(localStorage.getItem("allEntries"));
if (existingEntries == null) existingEntries = [];
var srno = document.getElementById("txtpid").value;
var name = document.getElementById("txtpname").value;
var dob = document.getElementById("txtpdob").value;
var email = document.getElementById("txtpemail").value;
var address = document.getElementById("txtpaddr").value;
var contact = document.getElementById("txtpmobile").value;
var obbbj = {
txtpid: srno,
txtpname: name,
txtpdob: dob,
txtpemail: email,
txtpaddr: address,
txtpmobile: contact
};
localStorage.setItem("details", JSON.stringify(obbbj));
existingEntries.push(obbbj);
localStorage.setItem("allEntries", JSON.stringify(existingEntries));
showEntry();
console.log(existingEntries);
//location.reload();
}
function showEntry() {
var messageBox = document.getElementById("display");
messageBox.value = "";
document.getElementById("txtpid").value = "";
document.getElementById("txtpname").value = "";
document.getElementById("txtpdob").value = "";
document.getElementById("txtpemail").value = "";
document.getElementById("txtpaddr").value = "";
document.getElementById("txtpmobile").value = "";
var render = "<table border='1'>";
render += "<tr><th>Srno</th><th>Name</th><th>Birthdate</th><th>Email</th><th>Address</th><th>Contact</th></tr>";
var allEntriesoo = {};
var detailsOOO = {};
for (i = 0; i < localStorage.length; i++) {
var key = localStorage.key(i);
var person = localStorage.getItem(key);
if (key == 'allEntries')
allEntriesoo = JSON.parse(person);
if (key == 'details')
detailsOOO = JSON.parse(person);
var data = JSON.parse(person);
}
for (var key in allEntriesoo) {
console.error(allEntriesoo[key])
render += "<tr><td>" + allEntriesoo[key].txtpid + "</td><td>" + allEntriesoo[key].txtpname + " </td>";
render += "<td>" + allEntriesoo[key].txtpdob + "</td>";
render += "<td>" + allEntriesoo[key].txtpemail + "</td>";
render += "<td>" + allEntriesoo[key].txtpaddr + "</td>";
render += "<td>" + allEntriesoo[key].txtpmobile + "</td>";
render += "<td><input type='button' value='Delete' onClick='return deleteEntry(" + i + ")'></td>";
render += "<td><input type='button' value='Edit' onClick='return editInfo(" + i + ")'></td></tr>";
}
render += "</table>";
display.innerHTML = render;
}
function nameVal() {
document.getElementById("txtpname").focus();
var n = document.getElementById("txtpname").value;
var r;
var letters = /^[a-zA-Z]+$/;
if (n == null || n == "") {
alert("please enter user name");
return null;
n.focus();
} else {
if (n.match(letters) && n != "") {
r = ValidateEmail();
return r;
} else {
alert("please enter alphabates");
document.getElementById("txtpname").value = "";
document.getElementById("txtpname").focus();
return null;
}
}
}
function ValidateEmail() {
var uemail = document.getElementById("txtpemail").value;
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (uemail.match(mailformat)) {
return true;
} else {
alert("You have entered an invalid email address!");
document.getElementById("txtpemail").value = "";
document.getElementById("txtpemail").focus();
return null;
}
}
function alphanumeric() {
var uadd = document.getElementById("txtpaddr").value;
var letters = /^[0-9a-zA-Z]+$/;
if (uadd == null || uadd == "") {
alert("plz enter address");
uadd.focus();
} else {
if (uadd.match(letters)) {
return true;
} else {
alert('User address must have alphanumeric characters only');
document.getElementById("txtpaddr").value = "";
document.getElementById("txtpaddr").focus();
return false;
}
}
}
function cntVal() {
var n = document.getElementById("txtpmobile").value;
var r1;
var letters = /^\d{10}$/;
if (n !== null || n !== "") {
if (n.match(letters)) {
r1 = alphanumeric();
return r1;
} else {
alert("please enter contact number");
document.getElementById("txtpmobile").value = "";
document.getElementById("txtpmobile").focus();
return null;
}
} else {
alert("please enter contact Number");
return null;
n.focus();
}
}
function deleteEntry(id) {
console.log("aaaaaaaaaaaaaaAAAA");
var entry = localStorage.getItem('allEntries') JSON.parse(localStorage.getItem('allEntries')): [];
var index;
for (var i = 0; i < entry.length; i++) {
if (entry[i].id === id) {
index = i;
break;
}
}
if (index === undefined) return
entry.splice(index, 1);
localStorage.setItem('entry', JSON.stringify(entry));
}
function clearstorage() {
localStorage.clear();
window.location.reload();
}
window.onload = function() {
showEntry();
};

In your deleteEntry function you are setting a new item in localStorage called 'entry'. So you are not setting 'allEntries' and thats probably why its showing up like that, 'allEntries' has not been updated. So just set all entries again. localStorage.setItem('allEntries', JSON.stringify(entry));
You are also missing the '?' for you variable 'entry'...
var entry = localStorage.getItem('allEntries') ? JSON.parse(localStorage.getItem('allEntries')) : []; <-- it should look like this.
Its the same as an 'if else statement'
function deleteEntry(id){
console.log("aaaaaaaaaaaaaaAAAA");
var entry = localStorage.getItem('allEntries') ? JSON.parse(localStorage.getItem('allEntries')) : [];
var index;
for (var i = 0; i < entry.length; i++) {
if (entry[i].id === id) {
index=i;
break;
}
}
if(index === undefined) return
entry.splice(index, 1);
localStorage.setItem('allEntries', JSON.stringify(entry)); <--- like this
}

You can use create a temporary object and then replace it in localStorage.
function deleteEntry(id){
console.log("aaaaaaaaaaaaaaAAAA");
var entry = JSON.parse(localStorage.getItem('allEntries'));
var temp= [];
for (var i = 0; i < entry.length; i++) {
if (entry[i].id !== id) {
temp.push(entry[i]);
}
}
localStorage.setItem('entry', JSON.stringify(temp));
}

Related

How to get string converted to array?

I am kind of new to this, but this is giving me a headache.
Heres my code what i am trying to solve:
function parseComponents(data: any, excelAttributesArray: string[]) {
let confs = "";
let isValues = false;
let listValues = "";
if (!data) return confs;
if (data["Part"]) {
const part = data["Part"];
excelAttributesArray.forEach((attribute) => {
let attributeValue = part[attribute];
if (attributeValue !== null) isValues = true;
if (attributeValue !== null && attributeValue.Value) {
attributeValue = attributeValue.Value;
}
listValues += attributeValue + ",";
});
const number = part["Number"];
if (isValues) {
confs += `${listValues}${number}`;
}
}
if (data["Components"] && data["Components"].length > 0) {
for (let i = 0; i < data["Components"].length; i++) {
const tmp = parseComponents(
data["Components"][i],
excelAttributesArray
);
if (tmp && tmp.length > 0)
confs += (confs.length > 0 ? "|" : "") + tmp;
}
}
return confs;
}
The confs value is returned as a string. How do i get it return as array?

Encode letter to number

I feel like I am failing everything this semester. but I was wondering if you all could help me with a JS project. We have been tasked with essentially converting numbers to letters and vica versa using textareas in HTML. I was able to do the numbers to letters function, but am having difficulties going the other way. what I have for all is:
var $ = function(id) {
return document.getElementById(id);
};
window.onload = function() {
$("btnDecode").onclick = fnDecode;
$("btnEncode").onclick = fnEncode;
$("btnClear").onclick = fnClear;
};
function fnDecode() {
var msg = $("textin").value;
if (msg === "") {
$("textin_span").innerHTML = "* Please enter a message to decode *";
$("textin").focus;
return;
} else {
$("textin_span").innerHTML = "";
}
var nums = msg.split(",");
var outstr = "";
for(var i=0; i < nums.length; i++) {
var n2 = parseInt(nums[i]);
if (isNaN(n2)) {
outstr += "?";
} else if (isNallN(nums[i])) {
} else if (n2 === 0) {
outstr += " ";
} else if (n2 < 1 || n2 > 26) {
outstr += "?";
} else {
outstr += String.fromCharCode(n2+64);
}
$("textout").value = outstr;
}
}
function isNallN(s) {
//parse string to check all characters are digits
}
function fnEncode() {
var msg = $("textin").value.toUpperCase();
$("textin").value = msg;
if (msg === "") {
$("textin_span").innerHTML = "* Please enter numberse to decode *";
$("textin").focus;
return;
} else {
$("textin_span").innerHTML = "";
}
var c;
var outstr = "";
for (var i=0; i<msg.length; i++);
c = msg.charCodeAt(i);
if (typeof c === "number") {
outstr += "99";
}else if (c === " ") {
outstr += 0;
/*} else if (c[i] >= "A" && c[i] <= "Z") {
outstr += "99";*/
} else {
outstr += String.charCodeAt(c - 64);
}
$("textout").value = outstr;
//var x = msg.charAT(i);
}
obviously isNallN is not complete, but he promised us if we could figure out fnEncode we should be able to do isNallN with no issues (which I am hoping is true lol) What am doing wrong though in fnEncode? Every time I run it, it gives me "99" even when I put letters in.

javascript function to add values outside of bracket into values inside the bracket

i am trying to create a function that automatically create questions to do.
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var totalvar = getRandomInt(2,4);
var main = "";
for (var i = 1; i <= totalvar; i++) {
var test = getRandomInt(1,3);
// alert(test);
var myArray = ["A","B","C","A&apos;","B&apos;","C&apos;"];
var text ="";
for (var a = 1; a <= test; a++) {
function random(array) {
return array[Math.floor(Math.random() * array.length)]
}
var testing = random(myArray);
if (testing =="A") {
var testing2 ="A&apos;";
} else if (testing =="A&apos;") {
var testing2 ="A";
} else if (testing =="B") {
var testing2 ="B&apos;";
} else if (testing =="B&apos;") {
var testing2 ="B";
}else if (testing =="C") {
var testing2 ="C&apos;";
} else if (testing =="C&apos;") {
var testing2 ="C";
}
//alert(testing);
//alert(myArray);
text += testing
var index = myArray.indexOf(testing);
if (index > -1) {
myArray.splice(index, 1);
}
var index = myArray.indexOf(testing2);
if (index > -1) {
myArray.splice(index, 1);
}
}
var brackets = getRandomInt(1,3);
var chances = getRandomInt(1,3);
var lastLetter = main.charAt(main.length - 1);
if (brackets == 1) {
text = "(" + text + ")";
if (main == "") {
main = text;
} else if ( lastLetter == ')') {
if ( chances !== 1) {
main += text;
}else
main += "+" + text;
}else
main += "+" + text;
} else {
if (main == "") {
main = text;
} else if ( lastLetter == ')') {
if ( chances !== 1) {
main += text;
}else
main += "+" + text;
}else
main += "+" + text;
}
}
I have manage to get it to display questions that i want
B'C'+(A'C'B')+BCA
B+(C')(CAB)
A'BC+(C')A+AB'
B'C'+AB(A'C'B')+BCA
I am stucked as i couldnt get the function for the next step where it multiples the value outside the bracket
B'C'+A'C'B'+BCA
B+C'CAB
A'BC+C'A+AB'
B'C'+ABA'C'B'+BCA
The above is what i hope to achieve but im unable to create the function out
any tips guys?
use replace:
var str = "B'C'+(A'C'B')+BCA";
var response = str.replace(/([\(\)]+)/g, '');
console.log(response);
// output: "B'C'+A'C'B'+BCA"

Check and alert for the null value

I need to check for the null values and alert them if there are any before getting saved. I have used this code but I am not able to alert the null values instead it is getting saved . .
function fn_publish() {
var SessionNames = getParameterByName('SessionName');
var MenuType = getParameterByName('MenuType');
var Date = getParameterByName('ForDate');
var publish = "Y";
Dates = Date.split("-");
Date = Dates[1] + "/" + Dates[2] + "/" + Dates[0];
var rows = [];
cols = document.getElementById('product_table').rows[1].cells.length - 1;
table = document.getElementById('product_table');
for (var i = 1; i <= cols; i++) {
for (var j = 0, row; row = table.rows[j]; j++) {
if (j == 0) {
cust = row.cells[i].innerText;
alert(cust);
} else if (j == 1) {
catlg = row.cells[i].innerText;
alert(catlg);
} else {
if (typeof (row.cells[i]) != "undefined") {
if (row.cells[i].innerText != "") {
//alert(SessionNames+"::"+MenuType+"::"+Date+"::"+catlg+"::"+row.cells[0].innerText+"::"+row.cells[i].innerText+"::"+cust+"::"+publish);
fn_insert(SessionNames, MenuType, Date, catlg, row.cells[0].innerText, row.cells[i].innerText, cust, publish);
} else {
jAlert("Please select a product", "ok");
return false;
}
}
}
}
}
jAlert("Menu Published", "ok");
}
if (row.cells[i].innerText != "") {
May be the cells are containing empty space in that. Better trim ad then compare.
if (row.cells[i].innerText.trim() !== "") {
Also instead of innerText use textContent which is common in most modern browsers.
if (row.cells[i].textContent.trim() !== "") {

Null error is coming document.getElementByid("dthchannel" + [i] is null)

function validate()
{
var flag=0;
var spchar=/^[a-zA-Z0-9 ]*$/;
var num=/^[0-9]*$/;
var custid = document.getElementById('CUSTOMERID').value;
var phoNo = document.getElementById('PHONENO').value;
var emailId = document.getElementById('EMAILID').value;
var channel = document.getElementById('CHANNELDTL').value;
if(channel=="")
{
alert("You have not selected any channel");
flag=1;
return false;
}
if(custid=="" || custid==null )
{
alert("Please enter Customer ID");
document.getElementById('CUSTOMERID').focus();
flag=1;
return false;
}
if (custid.search(num)==-1)
{
alert("Customer should be Numeric");
document.getElementById('CUSTOMERID').focus();
flag=1;
return false;
}
if(phoNo=="" || phoNo==null )
{
alert("Please enter Phone");
document.getElementById('PHONENO').focus();
flag=1;
return false;
}
if (phoNo.search(num)==-1)
{
alert("Phone should be Numeric");
document.getElementById('PHONENO').focus();
flag=1;
return false;
}
if(emailId=="" || emailId==null )
{
alert("Please enter Email");
document.getElementById('EMAILID').focus();
flag=1;
return false;
}
if (emailId)
{
if(isValidEmail(document.getElementById('EMAILID').value) == false)
{
alert("Please enter valid Email");
document.getElementById('EMAILID').focus();
flag=1;
return false;
}
}
if(flag==0)
{
var emailid=Base64.tripleEncoding(document.getElementById('EMAILID').value);
document.getElementById('E_EMAIL').value=emailid;
document.getElementById('EMAILID').value="";
var mobileno=Base64.tripleEncoding(document.getElementById('PHONENO').value);
document.getElementById('E_PHONE').value=mobileno;
document.getElementById('PHONENO').value="";
var customerid=Base64.tripleEncoding(document.getElementById('CUSTOMERID').value);
document.getElementById('E_CUSTID').value=customerid;
document.getElementById('CUSTOMERID').value="";
document.topupsform.action="../dth/leads/channelMail/channelMailUtil.jsp";
document.topupsform.submit();
alert("Thank you for choosing A-La-Carte services.\nWe will process it within 24 hours.\nYou will soon receive confirmation on your mail id.");
}
}
function isValidEmail(Email)
{
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var address = trim(Email);
if(reg.test(address) == false)
{
return false;
}
else
return true;
}
function trim(str)
{
str = this != window? this : str;
return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}
function sendMail()
{
caltotal();
validate();
}
//----------------------------------
var counter = 0;
function resetcheckboxValue(){
//var totalinputs = document.topupsform.getElementsByTagName("input");
var totalinputs =document.getElementsByName("dthchannel");
var totallenght = totalinputs.length;
counter = 0;
for(var i = 0; i < totallenght; i++) {
// reset all checkboxes
document.getElementsByName("dthchannel")[i].checked = false;
document.getElementById("totalamount").value = "0";
document.getElementById("youpay").value = "0";
}
}
function caltotal()
{
var plansObj = document.getElementsByName("dthchannel");
var plansLength = plansObj.length;
counter = 0;
var finalNameValue = "";
for(var i = 1; i <= plansObj.length+1; i++) {
if ( document.getElementById(("dthchannel")+ [i]).checked)
{
var gvalue = parseInt(document.getElementById(("dthchannel")+[i]).value);
var gNameValue= document.getElementById("CHANNELNAME"+i).value+"~"+gvalue+"#";
finalNameValue+= gNameValue;
counter+= gvalue;
}
showresult();
}
var finallist = finalNameValue.substring(0,finalNameValue.length-1);
//alert("finallist" +finallist);
document.getElementById("CHANNELDTL").value= finallist;
}
function showresult(){
if(counter <= 150 && counter > 0){
document.getElementById("youpay").value = "150";
document.getElementById("totalamount").value = counter;
}
else
{
document.getElementById("youpay").value = counter;
document.getElementById("totalamount").value = counter;
}
}
window.onload = resetcheckboxValue;
You need to modify whatever lines look like this:
var gvalue = parseInt(document.getElementById("dthchannel" + i).value);
You don't want to do document.getElementById(("dthchannel") + [i]) as I've never seen that before and I don't think it works.

Categories

Resources