Input value checked as unique and then added to Object Array - JavaScript - 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;

Related

Can't get value of array

Still can't understand my mistake with this code.
All what I want it - via prompt get all list of users (name / surname)
function UserList() {
let users = [];
while (true) {
let response = prompt('Please, enter your name surname?');
if (response == null) {
alert('cancel');
break;
}
users.push(response.split(' '));
}
return users;
}
function User() {
this.name = userList[0];
this.surname = userList[1];
this.regDate = new Date;
for (i = 0; i < userList.length; ++i) {
console.log('Name: ' + this.name + ' Surname: ' + this.surname + '. Date of registration : ' + this.regDate)
}
}
let userList = new UserList();
let user = new User();
And I faced with a misunderstanding why I cant get first word of prompt despite I put users.push (response.split(' ')).
userList [0] - shows first index of array instead first word.
And second I want to get all list of users in console.log but instead it I get the same string depending on length of array
userList[0] in the function User will return an array: ['name', 'surname'].
To get the first name for example, you need to use this.name = userList[i][0]
function UserList() {
let users = [];
while (true) {
let response = prompt('Please, enter your name surname?');
if (response == null) {
alert('cancel');
break;
}
users.push(response.split(' '));
}
return users;
}
function User() {
for (var i = 0; i < userList.length; ++i) {
this.name = userList[i][0];
this.surname = userList[i][1];
this.regDate = new Date;
console.log('Name: ' + this.name + ' Surname: ' + this.surname + '. Date of registration : ' + this.regDate)
}
}
let userList = new UserList();
let user = new User();
You are pushing an array in an other array, so your index is not correct (array looks like this: [["firstname", "lastname"]]). You could spread the items when pushing using the spread operator (...), you could also flatten the array using flat().
Also when creating a date, use new Date().
function UserList() {
let users = [];
while (true) {
let response = prompt('Please, enter your name surname?');
if (response == null) {
alert('cancel');
break;
}
users.push(...response.split(' ')); // flatten
}
return users;
}
function User() {
this.name = userList[0];
this.surname = userList[1];
this.regDate = new Date(); // ()
console.log('Name: ' + this.name + ' Surname: ' +
this.surname + '. Date of registration : ' + this.regDate)
}
let userList = new UserList();
let user = new User();
Using flat()
return users.flat();
Edit
I actually understood the question wrong (thought you only wanted 1 user), the other answer should be correct and makes more sense.
UserList shouldn't be a constructor. It should just be a function that returns an array of names.
You shouldn't be iterating over the list of users within User. You should then be iterating over the array creating one new User on each iteration which should be generated from a constructor. You can just pass in each name from the array and build an new object.
function getNames() {
const users = [];
while (true) {
const response = prompt('Please, enter your first and last names');
if (response == null) break;
users.push(response.split(' '));
}
return users;
}
// Pass in a user name from the array as an argument
// It's array so we can destructure the first and last name
// immediately
function User([first, last]) {
this.first = first;
this.last = last;
this.regDate = new Date();
this.message = `Name: ${this.first}. Surname: ${this.last}. Date of registration: ${this.regDate}.`;
}
// Iterate over the array generated by `getUsers`
// and for each name create a new user.
for (let name of getNames()) {
console.log(new User(name));
}
Additional documentation
Destructuring assignment

Delete element from array when deleting record from localStorage

I have a localStorage object like this:
Key: jpxun
Value: [{"id":"0","name":"royal"},{"id":"1","name":"tippins"},{"id":"4","name":"leviosa"},{"id":"5","name":"vicious"}]
I have this JS to display output the localStorage:
var jpxun = JSON.parse(localStorage.getItem('jpxun')) || [];
if (jpxun) {
var jpxun_length = jpxun.length;
} else {
var jpxun_length = 0;
}
var hst = document.getElementById("usernames");
var MyUsernames = JSON.parse(localStorage.getItem("jpxun"));
if (jpxun_length > 0) {
// declare array to hold items for outputting later in plain text format
var plain_text_array = [];
for (var i = 0; i < MyUsernames.length; i++) {
var un1 = MyUsernames[i].name;
hst.innerHTML += "<li>" +"<a id="+MyUsernames[i].id + " href='#content' onclick='deleteById(this)'>x </a>" + un1 + "</li>";
// add word to plain text array
plain_text_array.push(un1);
}
}
Each element is outputted in a list item with an 'x' as a hyperlink so that it can be clicked and that element is deleted from localStorage.
This is the code to delete the item from localStorage:
var deleteById = function ( self ){
MyUsernames = MyUsernames.filter(function(elem) {
return elem.id !== self.id;
});
localStorage.setItem("jpxun",JSON.stringify(MyUsernames));
self.parentNode.parentNode.removeChild(self.parentNode);
}
That works fine.
Unfortunately I don't really understand how the code works in deleteById.
As that is the case, I am stuck on working out how to delete the corresponding record from plain_text_array when its value is deleted from localStorage.
I would try to find the text in the array thats includes that string 'id="item_id"':
plain_text_array = plain_text_array.filter(item => !item.includes(`id="${self.id}"`));
Just add it in the end of deleteById function.

How I can get object from another function

I'm trying to do a Shopping cart with HTML and JS. So I'm using (https://www.smashingmagazine.com/2019/08/shopping-cart-html5-web-storage/).
In my function save(), I have,
`function save(id, title, price) {
// var button = document.getElementById('button');
// button.onclick=function(){
// var test = localStorage.setItem('test', id);
window.location.href='/panier'
var obj = {
title: title,
price: price
};
localStorage.setItem(id, JSON.stringify(obj));
var test = localStorage.getItem(id);
var getObject = JSON.parse(test);
console.log(getObject.title);
console.log(getObject.price);
}`
so to get "title for example I don't have problem in my function save(), but in my function doShowAll(),
function CheckBrowser() {
if ('localStorage' in window && window['localStorage'] !== null) {
// We can use localStorage object to store data.
return true;
} else {
return false;
}
}
function doShowAll() {
if (CheckBrowser()) {
var key = "";
var id = localStorage.getItem(id);
var list = "<tr><th>Item</th><th>Value</th></tr>\n";
var i = 0;
//For a more advanced feature, you can set a cap on max items in the cart.
for (i = 0; i <= localStorage.length-1; i++) {
key = localStorage.key(i);
list += "<tr><td>" + key + "</td>\n<td>"
+ localStorage.getItem(key) + "</td></tr>\n";
}
//If no item exists in the cart.
if (list == "<tr><th>Item</th><th>Value</th></tr>\n") {
list += "<tr><td><i>empty</i></td>\n<td><i>empty</i></td></tr>\n";
}
//Bind the data to HTML table.
//You can use jQuery, too.
document.getElementById('list').innerHTML = list;
} else {
alert('Cannot save shopping list as your browser does not support HTML 5');
}
}
I can't to get my object.
I have tried:
if (CheckBrowser()) {
var key = "";
var id = localStorage.getItem(id);
var getObject = JSON.parse(test);
}
var list = "<tr><th>Item</th><th>Value</th></tr>\n";
var i = 0;
//For a more advanced feature, you can set a cap on max items in the cart.
for (i = 0; i <= localStorage.length-1; i++) {
key = localStorage.key(i);
list += "<tr><td>" + key + "</td>\n<td>" + getObject.title
+ localStorage.getItem(key) + "</td></tr>\n";
}
but when I add something else than key or localStorage.getItem(key) in "list +=" nothing is displayed in my html view.
So I just Want to display data from my object in the PHP array in doShowAll() function.
Hoping to have clear and wainting a reply. Thank you

Array issues (javascript)

I created a small function that stores the book isbn, it's name and it's author. Everything is fine until I start to print out array. On every entery that completes the object into array, I want it to be printed one after another in new row, but this one is printing the objects from beginning every time when a new object is inserted. How do I fix this?
var books = [];
function blaBla(){
while(isbn != null || name != null || writer != null){
var isbn = window.prompt("Enter ISBN");
var name = window.prompt("Enter name of the book");
var writer = window.prompt("Enter name of the writer");
var patternString = /^[a-zA-Z]+$/;
var patternNum = /^[0-9]+$/;
if(isbn.match(patternNum)){
if(name.match(patternString)){
if(writer.match(patternString)){
books.push({
isbn: isbn,
name: name,
writer: writer
});
}
}
}
for (var i=0; i<books.length; i++){
document.write(books[i].isbn + " - " + books[i].name + " - " + books[i].writer + "</br>");
}
}
}
PS: How do I make it even more "cleaner", so when I hit cancel on prompt, it automatically stops with entering data into array, while, if i stop it on the "writer" prompt, it deletes previous entries for that object (last isbn and last name of the book)?
Thanks in advance.
You might want to give a little more context as to what this function is doing so we can help make your code cleaner as requested. I've separated the collection logic from the display logic here, and also used a while (true) loop with breaks on null or invalid inputs which will stop the collection of data.
Please note that prompt/alert boxes are a hideous way of collecting user input though (very awkward user experience). Consider using a table, input fields, and some jQuery instead to add rows and validate what the user has entered into input boxes.
var books = [];
function collectResponses() {
var patternString = /^[a-zA-Z]+$/;
var patternNum = /^[0-9]+$/;
while (true) {
var isbn = window.prompt("Enter ISBN");
if (!isbn || !isbn.match(patternNum)) {
break;
}
var name = window.prompt("Enter name of the book");
if (!name || !name.match(patternNum)) {
break;
}
var writer = window.prompt("Enter name of the writer");
if (!writer || !writer.match(patternNum)) {
break;
}
books.push({
isbn: isbn,
name: name,
writer: writer
});
}
}
function displayResponses() {
for (var i=0; i<books.length; i++){
document.write(books[i].isbn + " - " + books[i].name + " - " + books[i].writer + "</br>");
}
}

Filter string and return values

I have this simple variables
var string = 'this is string id="textID" name="textName" title="textTitle" value="textVal"';
var id, name, title, value;
I need to filter var string and get values for this variables id, name, title, value
How to do this?
I've used this function, as all your attributes have the same form, this works:
//
// inputs:
// strText: target string
// strTag: tag to search, can be id, name, value, title, ...
//
function getTagValue(strText, strTag)
{
var i, j, loffset = strTag.length + 2;
i = strText.indexOf(strTag + '="', 0);
if(i >= 0)
{
j = strText.indexOf('"', i + loffset);
if(j > i)
{
return strText.substring(i + loffset, j);
}
}
return "";
}
//
// main:
//
var string = 'this is string id="textID" name="textName" title="textTitle" value="textVal"';
var id, name, title, value;
console.log(string);
id = getTagValue(string, "id");
console.log(id);
name = getTagValue(string, "name");
console.log(name);
title = getTagValue(string, "title");
console.log(title);
value = getTagValue(string, "value");
console.log(value);
You can fetch the values by their indexes. Like I've done below:
var stringValue = 'this is string id="textID" name="textName" title="textTitle" value="textVal"';
var indexOfID=stringValue.indexOf('id'); // find the index of ID
var indexOfEndQuoteID=stringValue.indexOf('"',(indexOfID+4)); // find the index of end quote
var ID=stringValue.substring((indexOfID+4),(indexOfEndQuoteID)); // fetch the string between them using substring
alert(ID); // alert out the ID
Similarly you can do for other elements. Hope this helps..!

Categories