Item is not deleting from the array - javascript

I am trying to delete the item but cant get why the item is not removing from the array its in last line on delete item function but the item is not getting delete from data array i splice the array but thats also not work for me if there is any better solution plz help me out
Its in deleteitem function
//Constructor for student form
var studentForm = function(iD,name,city,college,course,age){
this.id = iD;
this.name = name;
this.city = city;
this.college = college;
this.course = course;
this.age = age;
}
//all data store here as object
var data = [];
//function to submit and display form
var submitForm = function(){
//getInput data from the field
var getInput = {
name:document.querySelector('.name').value,
city:document.querySelector('.city').value,
college:document.querySelector('.college').value,
course:document.querySelector('.course').value,
age:document.querySelector('.age').value,
}
//store the data which you get previous to use that
var input = getInput;
//Create a new id
var ID;
if(data.length > 0){
ID = data[data.length - 1].id +1;
}else{
ID =1;
}
//Use the constructor and make a new data
var newForm = new studentForm(ID,input.name,input.city,input.college,input.course,input.age);
//Add the student data into the ds
data.push(newForm);
//Display the data in the Document
//html line to display data of object
var html = '<tr id="id-%roll%"><td>%id%</td><td class="tname">%name%</td><td class="tcity">%city%</td><td class="tcollege">%college%</td><td class="tcourse">%course%</td><td class="tage">%age%</td><td><button class="delbtn">Delete</button></td></tr>';
//Replace the placeHOlder With actual data
var newHtml = html;
//newHtml = "<td class=\"id-%id%\">%id%</td>".replace(/%id%/g, ID)
newHtml = newHtml.replace('%roll%',ID);
newHtml = newHtml.replace('%id%',ID);
newHtml = newHtml.replace('%name%',input.name);
newHtml = newHtml.replace('%city%',input.city);
newHtml = newHtml.replace('%college%',input.college);
newHtml = newHtml.replace('%course%',input.course);
newHtml = newHtml.replace('%age%',input.age);
//Get the element which after you wants to print the data
document.querySelector('.tablemain').insertAdjacentHTML('beforeend',newHtml);
//Clearint the fields
var fields = document.querySelectorAll('.name' + ', ' + '.city' + ', ' + '.college' + ', ' + '.course' + ', ' + '.age');
//Convert it into array
var fieldsArr = Array.prototype.slice.call(fields);
//Loopthrough all fields to clear the fields
fieldsArr.forEach(function(current,index,array){current.value = '';});
fieldsArr[0].focus();
//Deleting element
// parent element class = table id = id delete button class =delbtn
console.log(newForm);
return newForm;
}
document.querySelector('.btn').addEventListener('click',submitForm);
//Delete section
//Deleting element
// parent element class = table id = id delete button class =delbtn
document.querySelector('.table').addEventListener('click',delItem);
function delItem(e){
var iTemId,splitID;
iTemId = e.target.parentNode.parentNode.id;
if(iTemId){
splitID = iTemId.split('-');
var ElementID = parseInt(splitID[1]);
var deleteItem = function(id){
var ids = data.map(function(cur){
return cur.id;
});
var index = ids.indexOf(id);
if(index !== -1){
data.slice(index,1);
}
};
deleteItem(ElementID);
};
};
<input type="text" placeholder="name" class="name">
<input type="text" placeholder="city" class="city">
<input type="text" placeholder="college" class="college">
<input type="text" placeholder="Course" class="course">
<input type="number" placeholder="age" class="age">
<button class="btn" value="submit">Submit</button>
<div class="table">
<table class="tablemain">
<tr class="table-heading"><th>ID</th><th>Name</th><th>City</th><th>College</th><th>Course</th><th>Age</th><th>Delete</th></tr>
</table>
</div>

Splice and Slice both are JavaScript Array functions. The splice() method returns the removed item(s) in an array while mutating the original array and slice() method returns the selected element(s) in an array, as a new array object without mutating the original array.
What you have used here is slice instead of splice. If you want to use slice, return the resulting array or replace slice with splice
if(index !== -1){
data.splice(index,1);
}
// Or
if(index !== -1){
const newData = data.slice(index,1);
}

For future questions, you'll get more responses if you can simplify your question as much as possible. The code you posted is a little tough to grok.
That being said, I think the issue is here data.slice(index,1);. Array.prototype.slice does not mutate the original array. It returns a new array. For this reason, sometimes folks use it to create copies of an array to avoid mutation with something like const arrCopy = originalArr.slice();.
I think you are looking for the array splice method.
Hope this gets you closer. Where is data declared? I see you're doing all sorts of things to it and treating as a global var but not sure where you declare it.

I just modified delItem function
delete table row
set index to -1 (because array starts from 0)
//Constructor for student form
var studentForm = function(iD,name,city,college,course,age){
this.id = iD;
this.name = name;
this.city = city;
this.college = college;
this.course = course;
this.age = age;
}
//all data store here as object
var data = [];
//function to submit and display form
var submitForm = function(){
//getInput data from the field
var getInput = {
name:document.querySelector('.name').value,
city:document.querySelector('.city').value,
college:document.querySelector('.college').value,
course:document.querySelector('.course').value,
age:document.querySelector('.age').value,
}
//store the data which you get previous to use that
var input = getInput;
//Create a new id
var ID;
if(data.length > 0){
ID = data[data.length - 1].id +1;
}else{
ID =1;
}
//Use the constructor and make a new data
var newForm = new studentForm(ID,input.name,input.city,input.college,input.course,input.age);
//Add the student data into the ds
data.push(newForm);
//Display the data in the Document
//html line to display data of object
var html = '<tr id="id-%roll%"><td>%id%</td><td class="tname">%name%</td><td class="tcity">%city%</td><td class="tcollege">%college%</td><td class="tcourse">%course%</td><td class="tage">%age%</td><td><button class="delbtn">Delete</button></td></tr>';
//Replace the placeHOlder With actual data
var newHtml = html;
//newHtml = "<td class=\"id-%id%\">%id%</td>".replace(/%id%/g, ID)
newHtml = newHtml.replace('%roll%',ID);
newHtml = newHtml.replace('%id%',ID);
newHtml = newHtml.replace('%name%',input.name);
newHtml = newHtml.replace('%city%',input.city);
newHtml = newHtml.replace('%college%',input.college);
newHtml = newHtml.replace('%course%',input.course);
newHtml = newHtml.replace('%age%',input.age);
//Get the element which after you wants to print the data
document.querySelector('.tablemain').insertAdjacentHTML('beforeend',newHtml);
//Clearint the fields
var fields = document.querySelectorAll('.name' + ', ' + '.city' + ', ' + '.college' + ', ' + '.course' + ', ' + '.age');
//Convert it into array
var fieldsArr = Array.prototype.slice.call(fields);
//Loopthrough all fields to clear the fields
fieldsArr.forEach(function(current,index,array){current.value = '';});
fieldsArr[0].focus();
//Deleting element
// parent element class = table id = id delete button class =delbtn
console.log(newForm);
return newForm;
}
document.querySelector('.btn').addEventListener('click',submitForm);
//Delete section
//Deleting element
// parent element class = table id = id delete button class =delbtn
document.querySelector('.table').addEventListener('click',delItem);
function delItem(e){
// Delete table row
document.getElementById(e.target.parentNode.parentNode.id).remove();
var iTemId,splitID;
iTemId = e.target.parentNode.parentNode.id;
if(iTemId){
splitID = iTemId.split('-');
var ElementID = parseInt(splitID[1]);
var deleteItem = function(id){
var ids = data.map(function(cur){
return cur.id;
});
var index = ids.indexOf(id);
if(index !== -1){
// delete array in data (array start with 0)
data = data.slice(index-1,1);
}
};
deleteItem(ElementID);
};
};
<input type="text" placeholder="name" class="name">
<input type="text" placeholder="city" class="city">
<input type="text" placeholder="college" class="college">
<input type="text" placeholder="Course" class="course">
<input type="number" placeholder="age" class="age">
<button class="btn" value="submit">Submit</button>
<div class="table">
<table class="tablemain">
<tr class="table-heading"><th>ID</th><th>Name</th><th>City</th><th>College</th><th>Course</th><th>Age</th><th>Delete</th></tr>
</table>
</div>

Related

How to arrange the output in alphabetical order in javascript?

I need help as soon as possible.
I try have tried various way on how to arrange the output in alphabetical order but none of them seems work.
The question is asked to arrange the output in alphabetical order without changing the base code.
The base code:
function add() {
var name = document.getElementById("id-name").value;
var address = document.getElementById("id-address").value;
var content = document.getElementById("id-content").innerHTML;
document.getElementById("id-content").innerHTML = content + name + "<br/>" + address + "<hr/>";
}
Name: <input type="text" id="id-name" name="name"><br /> Address: <textarea id="id-address" name="address"></textarea><br />
<button id="id-send" onclick="javascript: add();">Send</button>
<hr>
<div id="id-content"></div>
This is the example of the output that it should display:
You could create an array and sort it
I wrapped in a form to have simpler event handling. Also no need for javascript: label on an inline event handler
const list = []; // you can get this from localStorage if you want to save across reloads
window.addEventListener("DOMContentLoaded", () => {
const content = document.getElementById("id-content"),
nameField = document.getElementById("id-name"),
addressField = document.getElementById("id-address");
const show = () => {
list.sort((a, b) => a.name.localeCompare(b.name))
content.innerHTML = list.map(({ name, address }) => `${name}<br/>${address}`).join("<hr/>");
};
document.getElementById("myForm").addEventListener("submit", e => {
e.preventDefault();
const name = nameField.value;
const address = addressField.value;
list.push({ name, address });
show();
});
});
<form id="myForm">
Name: <input type="text" id="id-name" name="name"><br /> Address: <textarea id="id-address" name="address"></textarea><br />
<button id="id-send">Send</button>
</form>
<hr>
<div id="id-content"></div>
You could keep an array of submitted data and sort the array alpabetically. This solution should work:
let listOfData = [];
function add() {
var name = document.getElementById("id-name").value;
var address = document.getElementById("id-address").value;
var content = document.getElementById("id-content").innerHTML;
listOfData.push({
personName: name,
personAddress: address
});
document.getElementById("id-content").innerHTML = "";
listOfData.sort((a, b) => a.personName.localeCompare(b.personName));
for (let person of listOfData) {
document.getElementById(
"id-content"
).innerHTML += `${person.personName} <br/> ${person.personAddress}<br/> <hr/>`;
}
}
Use this code it will work
function add() {
var name = document.getElementById("id-name").value;
var address = document.getElementById("id-address").value;
let data = document.getElementById("id-content");
let content = data.innerHTML;
content = content + name + "<br/>" + address + "<hr>";
let dt = "";
let sortArr = content.split("<hr>").sort().join().split(",");
for (let i = 1; i < sortArr.length; i++) {
dt += sortArr[i] + "<hr>";
}
data.innerHTML = dt;
}

Javascript cell.innerHTML() displays [object HTMLDivElement]

I have:
var cboxHTMLString = "<input type='checkbox' class='custom-control-input'"
+ "id='customCheck1' name=${" + check_name + "}>"
+ "<label class='custom-control-label' for='customCheck1'>"
+ "</label>";
var div = document.createElement('div');
div.setAttribute("class", "custom-control custom-checkbox");
var checkbox_div = createElementFromHTML(cboxHTMLString, div);
The function being called is:
function createElementFromHTML(htmlString, element){
element.innerHTML = htmlString.trim();
return element; //.childNodes;
};
I then fill an object with the new key-value and other key-values I received from php/mysql:
var d_dict = {Select: checkbox_div};
//iterate disease_dict and add k,v to d_dict
for(let key in disease_dict) {
var new_key = key;
var new_val = disease_dict[key];
d_dict[new_key] = new_val;
}
Then I fill my table cells:
for(let key in d_dict){
let cell = row.insertCell(-1);
if(key==='Select'){
var checkbox_html = d_dict[key];
cell.innerHTML = checkbox_html;
console.log(cell);
}
else{
let val = d_dict[key];
let newText = document.createTextNode(val);
cell.appendChild(newText);
console.log(cell);
}
}
But it shows the text instead of the checkbox.
Edit:
I did
for(k in checkbox_html){
console.log(checkbox_html[k]);
}
and it showed me a bunch of integers:
What does that mean?
Your createElementFromHTML() function returns a DOM element object, not a string of HTML:
var checkbox_div = createElementFromHTML(cboxHTMLString, div);
Because it is a DOM element, you must use the .appendChild() method to append it to the cell:
if(key==='Select'){
var checkbox_html = d_dict[key];
cell.appendChild( checkbox_html );
}

Remove a specific item from localstorage with js

I am adding simple records to localstorage but I am having a hard time removing a specific item from my localstorage object. I am able to maintain the data on refresh and continue adding records no problem. I would like to add a button next to each entry that allows me to remove THAT particular record from localstorage and from my list.
How would I accomplish this given the code below?
var theLIst = document.getElementById('list');
var resetNotify = document.getElementById('reset-message');
var recordCounter = document.getElementById('record-counter');
var st = window.localStorage;
var count = st.clickcount;
var nameArray = [];
var newArr;
// Set the counter on refresh
if (JSON.parse(st.getItem('names'))) {
recordCounter.innerHTML = (count = JSON.parse(st.getItem('names')).length);
theLIst.innerHTML = st.getItem('names').replace(/[\[\\\],"]+/g, '');
} else {
recordCounter.innerHTML = (count = 0);
}
function addNameRecord() {
resetNotify.innerHTML = '';
var name = document.getElementById('names-field');
nameArray = JSON.parse(st.getItem('names'));
count = Number(count) + 1;
newArr = makeArr(nameArray);
// Check if there is anything in the name array.
if (nameArray != null) {
nameArray.push('<p class="name-entry"><strong>' + count + '. </strong> ' + name.value + '</p><button onclick="clearThisItem(\''+ name.value + '\')">Remove</button>');
} else {
nameArray = [];
nameArray.push('<p class="name-entry"><strong>' + count + '. </strong> ' + name.value + '</p><button onclick="clearThisItem(\''+ name.value + '\')">Remove</button>');
}
st.setItem("names", JSON.stringify(nameArray));
name.value = '';
if (!newArr[0]) {
count = 1;
theLIst.innerHTML = nameArray;
recordCounter.innerHTML = count;
} else {
theLIst.innerHTML = newArr[0].join('');
recordCounter.innerHTML = count;
}
}
// Take our string from local storage and turn it into an array we can use
function makeArr() {
return Array.from(arguments);
}
// Purge all entries, reset counter
function clearArray() {
st.clear();
nameArray = [];
theLIst.innerHTML = '';
recordCounter.innerHTML = (count = 0);
resetNotify.innerHTML = 'Array has been purged.';
}
Heres the code I tried
// Delete a specific entry
function clearThisItem(item) {
console.log(item);
localStorage.removeItem(item);
console.log(localStorage.removeItem(item))
return item;
}
Here is refactored code.
Firstly there is no need to store count, as we always have access to names.length
Store only names on localStorage, not entire HTML
For add and remove a name, fetch names array from localStorage, update it and save it back to localStorage.
After every action just update the UI using a single function call.
Note: Renamed names-field to name-field in the below implementation.
Here is the working code: https://jsbin.com/simitumadu/1/edit?html,js,output
var $list = document.getElementById('list');
var $resetMessage = document.getElementById('reset-message');
var $resetCouter = document.getElementById('record-counter');
var names = getNames();
if(names == null){
setNames([]); // initializing the empty array for first time.
}
renderData(); // display data
function addNameRecord() {
$resetMessage.innerHTML = '';
var name = document.getElementById('name-field');
addName(name.value);
renderData();
name.value = ''; //clear input field
}
function renderData(){
var names = getNames();
$resetCouter.innerText = names.length; // Count
var namesListHTML = '';
names.forEach(function(name, index){
namesListHTML = namesListHTML + '<p class="name-entry"><strong>' + (index + 1) + '. </strong> ' + name + '</p><button onclick="clearThisItem(\'' + name + '\')">Remove</button>'
});
$list.innerHTML = namesListHTML;
}
function clearArray() {
setNames([]); // clear names
$resetMessage.innerHTML = 'Array has been purged.';
renderData();
}
function clearThisItem(name){
removeName(name); // remove from localStorage
renderData();
}
function getNames(){
namesStr = localStorage.getItem('names');
if(namesStr) {
return JSON.parse(namesStr);
}
return null;
}
function setNames(names){
return localStorage.setItem('names', JSON.stringify(names));
}
function addName(name){
var names = getNames();
names.push(name);
setNames(names);
}
function removeName(name){
var names = getNames();
var index = names.indexOf(name);
if (index > -1) {
names.splice(index, 1);
}
setNames(names);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<p>Count : <span id="record-counter"></div></p>
<input id="name-field">
<button onclick="addNameRecord()">Add</button>
<button onclick="clearArray()">Clear</button>
<div id="list"></div>
<div id="reset-message"></div>
</body>
</html>
Use localStorage.removeItem(insertYourKeyHere); to remove an object from local storage.
For removing it from your nameArray you can search through your list for the record, set null and then sort your list by ensuring to move objects into new positions such that null is at the end, then decrement your count for the number of records

Input value checked as unique and then added to Object Array - JavaScript

So I'm trying to design a form that will have 3 input fields (Cust ID, Cust Name and Amount), the ID would need to be checked if it exists in the Object Array, and if so throw an error, otherwise it would add all 3 values to the Object Array.
I need to use an object so that I don't use a multitude of Arrays, however I've never actually used an Object based Array, so if anyone is able to provide an example of how to use it that would be a massive help!
var garrCust = {id:"", name:"", amount:""};
function addCust(){
var custID = document.getElementById("custid").value;
var custName = document.getElementById("custname").value;
var amount = document.getElementById("amount").value;
if(!custID){
document.getElementById("output").innerHTML = "ID Cannot be Blank";
return false;}
document.getElementById("output").innerHTML += "<br />Added " + custID + "<br /><br />";
document.getElementById("output").innerHTML += "List contains: " + garrCust.id;
return true;
}
I would use an ID to name-and-amount object map to simplify and speed-up the lookup:
var garrCust = []; // an array of id -> {id:"", name:"", amount:""}
function addCust(){
var custID = document.getElementById("custid").value;
var custName = document.getElementById("custname").value;
var amount = document.getElementById("amount").value;
if(!custID){
document.getElementById("output").innerHTML = "ID Cannot be Blank";
return false;
}
if (!garrCust[custID]) {
// ID not found in the array
garrCust[custID] = { id: custID, name : custName, 'amount' : amount};
document.getElementById("output").innerHTML += "<br />Added " + custID + "<br /><br />";
} else {
document.getElementById("output").innerHTML += "List contains: " + garrCust.id;
}
return true;
}
NOTE: Storing ID as part of object is actually optional as it is already associated with an entry as an array index
You may also use a constructor to define the object content and the id as the property to index them like so:
// Create an object with the two properties name and amount
function Customer(name,amount) {
this.name = name;
this.amount = amount;
}
// Declare some variables
var id, c;
var customers = {};
// Sample names
var name = [ 'one','two','three','four','five' ];
// Create five sample entries - reusing id for amount
for (id = 0; id < 5; id++) {
// Using the new keyword with customer creates the object with
// the data you pass
customers[id] = new Customer(name[id],id);
}
// A loop to test for the presence of customer ids
for (c = 0; c < 5; c++) {
id = Math.floor(Math.random() * 20);
if (customers.hasOwnProperty(id)) {
console.log(id+" exists");
} else {
console.log(id+" does not exist");
}
}
This would create an object that had objects as properties, and the name of the properties is the customer id.
customers = { 44: { name: "John", amount: 6 },
33: { name: "Sally", amount: 5}};
To display the customer list, you may use the following:
var html;
// Use a template literal to build the list item for each customer
function listTemplate(id,name,amount) {
return `<li><span class="id">${id}</span>
<span class="name">${name}</span>
<span class="amount">${amount}</span></li>`;
}
html = "<ul>";
// Iterate through all the customers
for (id in customers) {
c = customers[id];
// Concatenate the list items
html += listTemplate(id,c.name,c.amount);
}
html += "</ul>";
// Add the HTML into the DOM
document.getElementById("customer-list").innerHTML = html;

get stuck to add and manage multiple javascript input instances to list

trying to do javascript app that should have 4 inputs - user, mail, phone address
add new user / delete user details to/from the list buttons (popup should appear to confirm). Get stuck adding multiple users.
here is the code in a jsfiddle
The var seem to be objects HTMLElements
<div class="container">
<p>
<label for="new-task">Add Item</label><input id="new" type="text"><input id="new" type="text"><input id="new" type="text"> <input id="new" type="text"><button>Add</button>
</p>
<h3>Todo</h3>
<ul id="current-tasks">
<li><label> Learn </label><button class="delete">Delete</button></li>
<li><label>Read</label><button class="delete">Delete</button></li>
</ul>
<script>
var nameInput = document.getElementById("new-name");
var emailInput = document.getElementById("new-email");
var noInput = document.getElementById("new-phone");
var zipInput = document.getElementById("new-zip");
// var = nameInput + " " + emailInput + " " + noInput + " " + zipInput;
// console.log(nameInput);
// console.log(taskInput.innerText);
// var taskInput = nameInput.concat(emailInput);
// document.querySelectorAll("new-name, new-email, new-number, new-zip");
// var taskInput = nameInput + " " + emailInput + " " + noInput + " " + zipInput;
// var taskInput = nameInput.concat(emailInput);
// document.querySelectorAll("new-name, new-email, new-number, new-zip");
var addButton = document.getElementsByTagName("button")[0]; //first button
var cTasksHolder = document.getElementById("current-tasks"); //current-tasks
var delButton= document.getElementsByClassName("delete");
//New Task List Item
var createNewTaskElement = function(taskString) {
//Create List Item
var listItem = document.createElement("li");
var label = document.createElement("label");
var deleteButton = document.createElement("button");
deleteButton.innerText = "Delete";
deleteButton.className = "delete";
label.innerText = taskString;
//each element need appending
listItem.appendChild(label);
listItem.appendChild(deleteButton);
return listItem;
alert(listItem);
}
// adauga task
var addTask = function() {
console.log("Add task...");
var nnameInput = nameInput.value;
var nemailInput = emailInput.value);
var nnoInput = noInput.value;
var nzipInput = zipInput.value);
var tInput = [nnameInput, nemailInput , nnoInput, nzipInput];
var taskInput = tInput.join(", ");
alert(taskInput.value);
alert(taskInput);
var listItem = createNewTaskElement(taskInput.value);
console.log(taskInput.value);
//apend listItems to imcomplete taskHolder (only if task is not null)
if(taskInput.value) {
cTasksHolder.appendChild(listItem);
bindTaskEvents(listItem);
} else {
alert("You must enter the name , the email , the phone and the zip code.");
}
}
var deleteTask = function() {
console.log("Delete task...");
var listItem = this.parentNode;
var ul = listItem.parentNode;
ul.removeChild(listItem);
}
var bindTaskEvents = function(taskListItem){
console.log("Bind list item events");
var deleteButton = taskListItem.querySelector("button.delete");
deleteButton.onclick = deleteTask;
} addButton.onclick = addTask;
for (var i = 0; i < cTasksHolder.children.length; i++) {
console.log(cTasksHolder.children[i]);
bindTaskEvents(cTasksHolder.children[i]);
}
</script>
You are missing the call for the values of the inputs. When you call at the beginning the document.getElementById(), you use this var to create stuff, when what you need is it's value, like so:
var nameInput = document.getElementById("new-name")
var nnameInput = nameInput.value;
EDIT - There was multiple wrong things, I'll list them here along with an updated jsfiddle.
In addTask, you had the line "console.log(string);;", it was crashing because of double ";" and because you were trying to print a 'string' var, that didn't exist.
You didn't add ".value" when you call "nameInput" so the code was working with elements rather than strings.
There was no need to write "var nnameInput = nameInput;" in function addTask
You wrote "var listItem = createNewTaskElement(taskInput.value);" but there was no need for the value, as the taskInput is already a string that was joined by ',' previously.
And you do the same as the above in the "if (taskInput.value) {", where it should be "if (taskInput) {"
http://jsfiddle.net/filipetedim/u27Lytqt/4/

Categories