Clear a Map Object - javascript

I just started learning javascript. Today trying to learn Map Object Key and Value Pairs. but somehow I see a nonfunctional method of Map namely clear().
whole code I posted below. and line34 and line36 prints same map pairs albeit map object clear method already invoked. where am I wrong ? I just wanna clear the Map object named list_
here is a link you can test and see weirdness: https://codepen.io/KTURKAY/pen/oEpXgb
var list_ = new Map();
var inputkey;
var inputvalue;
var buttonadd;
var buttonclear;
var divlist;
function buttonclearclick(el, ev) {
divlist.innerHTML = '';
console.log(list_);
list_.clear();//I expected, this method should clear it. but indeed it doesn't.?
console.log(list_);
}
function buttonaddclick(c, e) {
list_[inputkey.value] = inputvalue.value;
divlist.innerHTML = "";
for (x in list_) {
let n = document.createElement('div');
n.innerHTML = `${x} = ${list_[x]}`;
divlist.appendChild(n);
}
}
document.body.onload = function(ev) {
inputkey = document.getElementById('inputkey');
inputvalue = document.getElementById('inputvalue');
buttonadd = document.getElementById('buttonadd');
buttonclear = document.getElementById('buttonclear');
divlist = document.getElementById('divlist');
buttonadd.addEventListener('click', buttonaddclick);
buttonclear.addEventListener('click', buttonclearclick);
}
<form>
KEY:
<input type="text" id="inputkey" /> VALUE:
<input type="text" id="inputvalue" />
<input type="button" value="ADD" id="buttonadd" />
<input type="button" value="CLEAR" id="buttonclear" />
</form>
<div id="divlist">
NO DATA
</div>

Some issues:
The items are retrieved in the wrong way from the map. Use the .get method.
The items are not iterated in the correct way. Use for ... of instead of for ... in
See updated script running correctly in this snippet. Comments indicate the corrections:
var list_ = new Map();
var inputkey;
var inputvalue;
var buttonadd;
var buttonclear;
var divlist;
function buttonclearclick(el, ev) {
divlist.innerHTML = '';
console.log('before: ' + list_.size); // To make it work in this snippet
list_.clear();
console.log('after: ' + list_.size); // To make it work in this snippet
}
function buttonaddclick(c, e) {
list_.set(inputkey.value, inputvalue.value); // Use set
divlist.innerHTML = "";
for (const [key, value] of list_) { // Get entries using `of`
const n = document.createElement('div');
n.textContent = `${key} = ${value}`; // Use pair coming from iterator
divlist.appendChild(n);
}
}
document.body.onload = function (ev) {
inputkey = document.getElementById('inputkey');
inputvalue = document.getElementById('inputvalue');
buttonadd = document.getElementById('buttonadd');
buttonclear = document.getElementById('buttonclear');
divlist = document.getElementById('divlist');
buttonadd.addEventListener('click', buttonaddclick);
buttonclear.addEventListener('click', buttonclearclick);
}
<form>
KEY:
<input type="text" id="inputkey" /> VALUE:
<input type="text" id="inputvalue" />
<input type="button" value="ADD" id="buttonadd" />
<input type="button" value="CLEAR" id="buttonclear" />
</form>
<div id="divlist">
NO DATA
</div>

The problem is this:
list_[inputkey.value] = inputvalue.value;
You need to use get and set to work with Maps:
list_.set(inputkey.value, inputvalue.value);
Calling clear() does remove all key/values from the internal Maps Hashmap, but it does not clear the object properties. And if you use the first way of setting properties, you dont actually need a Map but you can use a plain object.

Related

calculating from an input

I'm starting studying the DOM in javascript and I'd like to create a program which makes the sum of two numbers given on input and show it.
I'd like to know what functions should I use, and what functions it is better I didn't.
This is my (very simple) html code:
let warp = document.getElementById('warp');
let first = document.getElementById('first').value;
let one = parseInt(first);
let second = document.getElementById('second').value;
let two = parseInt(second);
let res = document.getElementById('res');
//res.addEventListener('click', calcul);
//res.onclick(calcul);
let nouveau = document.createElement('div');
nouveau.id = 'nouveau';
nouveau.textContent = "nouveau";
warp.appendChild(nouveau);
function calcul(first, second) {
console.log(one + two);
event.preventDefault();
}
<!DOCTYPE html>
</head>
<body>
<div id="warp">
<form>
<input id="first" type="number">first number</input>
<input id="second" type="number">second number</input>
<input id="res" type="submit" value="Envoyer" onclick="calcul()" />
</form>
<div>
</body>
let answerElemenet = document.createElement("h1");
// You can create a h1 element to display your answer after calculating it
document.body.appendChild(answerElemenet);
// Inside the calculate Function you get the values of input one and two
// and then you store the sum value in a variable and just change your
// answerElement to have the innerHTML value of the finalSum Variable
function calculate(){
let valueOne = parseFloat(document.getElementById('first').value);
let valueTwo = parseFloat(document.getElementById('second').value);
let finalSum = valueOne + valueTwo;
answerElemenet.innerHTML = finalSum;
}
Welcome to Stackoverflow!
I copied your answer and made some small changes. Here comes a brief description and explanation of what you could do better:
If you don't plan to change these references use const instead of let. Also try to keep input elements separated from their values. The reference to the input probably won't change but their value most certainly will.
const warp = document.getElementById('warp');
const first = document.getElementById('first');
const second = document.getElementById('second');
const res = document.getElementById('res');
When calculating input values, you usually want them as fresh as possible so instead of saving input values right at the beginning of the script, you get them when you need them, in the calcul() function.
You will also need some kind of validation. Here we try to convert the input to a number and set to zero if not possible:
function calcul() {
event.preventDefault();
const one = parseFloat(first.value) || 0;
const two = parseFloat(second.value) || 0;
console.log(one + two);
}
The preferred way of adding event handlers to DOM elements is using the event API. So to call the calcul()function you use the line you had commented:
res.addEventListener('click', calcul);
This also means you should remove the onClick attribute from the DOM. Also, input cannot have children:
<input id="first" type="number" />
<input id="second" type="number" />
<input id="res" type="submit" value="Envoyer"/>
All together looks like this:
const warp = document.getElementById('warp');
const first = document.getElementById('first');
const second = document.getElementById('second');
const res = document.getElementById('res');
function calcul() {
event.preventDefault();
const one = parseFloat(first.value) || 0;
const two = parseFloat(second.value) || 0;
console.log(one + two);
}
res.addEventListener('click', calcul);
let nouveau = document.createElement('div');
nouveau.id = 'nouveau';
nouveau.textContent = "nouveau";
warp.appendChild(nouveau);
<!DOCTYPE html>
</head>
<body>
<div id="warp">
<form>
<input id="first" type="number" />
<input id="second" type="number" />
<input id="res" type="submit" value="Envoyer"/>
</form>
<div>
</body>
Keep up the good job and never stop asking questions!
This will work. You just need to call the values based on their id in the calcul() function itself.
let warp = document.getElementById('warp');
let res = document.getElementById('res');
let nouveau = document.createElement('div');
nouveau.id = 'nouveau';
nouveau.textContent = "nouveau";
warp.appendChild(nouveau);
function calcul() {
let first = document.getElementById('first').value;
let one = parseInt(first);
let second = document.getElementById('second').value;
let two = parseInt(second);
if(isNaN(one) || isNaN(two)){
event.preventDefault();
return
}
console.log(one + two);
event.preventDefault();
}
<!DOCTYPE html>
</head>
<body>
<div id="warp">
<form>
<input id="first" type="number">first number</input>
<input id="second" type="number">second number</input>
<input id="res" type="submit" value="Envoyer" onclick="calcul()" />
</form>
<div>
</body>

JSON stringify is showing object object after refresh

inputting the data is fine, submitting is fine. But, if I refresh, everything that was inputted displays as object object. Any idea's why?
In addition to this, each input creates table data but seperately rather than in a table and each input puts each newly created data side by side whereas I want them to space-around like justify-content: space-around. But it doesn't seem to be doing that
Still new to JS. I couldn't find exactly what i'm doing wrong. JSON stringify is still a new practice for me too. So, I am unsure if what I have done is correct.
EDIT ------------------------
Can anyone explain what is happening with the formatting after a refresh ?
html
<h1>Library</h1>
<div id="login" class="login-btn">
<button class="User" id = "login">login</button>
</div>
<button id="clear">Clear</button>
<form id="form" action="">
<input class="input" type="text" id="input-title" placeholder="Title" required />
<input class="input" type="text" id="input-author" placeholder="Author" required/>
<input class="input" type="number" id="input-number" placeholder="Pages" required />
<input value="Submit" id="submitbtn" class="submit" type="submit">
</form>
<input type="checkbox" class="checkbox"><span> Check me if you read the book</span>
<table id="table">
</table>
<script src="script.js"></script>
</body>
</html>
js
//buttons
const buttonLogin = document.getElementById("login")
const table = document.getElementById("table")
const clearBtn = document.getElementById("clear")
const submitBtn = document.getElementById("submitbtn")
const form = document.getElementById("form")
const inputTitle = document.getElementById("input-title")
const inputAuthor = document.getElementById("input-author")
const inputNumber = document.getElementById("input-number")
//array local storage
let itemsArray = localStorage.getItem('items')
? JSON.parse(localStorage.getItem('items'))
: []
localStorage.setItem('items', JSON.stringify(itemsArray))
const data = JSON.parse(localStorage.getItem('items'))
const createBook = (text, text1, text2) => {
const tble = document.createElement('table')
const td = document.createElement('td')
const td2 = document.createElement('td')
const td3 = document.createElement('td')
td.textContent = text
td.style.color = ('black')
td.style.border = ('solid')
td.style.borderColor =('blueviolet')
td2.textContent = text1
td2.style.color = ('black')
td2.style.border = ('solid')
td2.style.borderColor = ('blueviolet')
td3.textContent = text2
td3.style.color = ('black')
td3.style.border = ('solid')
td3.style.borderColor =('blueviolet')
table.appendChild(td)
table.appendChild(td2)
table.appendChild(td3)
}
form.addEventListener('submit', function (e) {
e.preventDefault()
//for (var i = 0; i < 2; i++) {
itemsArray.push(inputTitle, inputAuthor, inputNumber)
localStorage.setItem('items', JSON.stringify(itemsArray))
createBook(inputTitle.value, inputAuthor.value, inputNumber.value)
inputTitle.value = ''
inputAuthor.value= ''
inputNumber.value= ''
// }
})
data.forEach ((item) => {
createBook(item)
})
//clear list
clearBtn.addEventListener('click', function () {
localStorage.clear()
while (table.firstChild) {
table.removeChild(table.firstChild)
}
})
You need to save the values of the inputs, not the input elements themselves. And the values for a single item should be collected together into an array or object.
itemsArray.push([inputTitle.value, inputAuthor.value, inputNumber.value])
Also, when you process the data, you need to spread the array into separate arguments to createBook().
data.forEach ((item) => {
createBook(...item)
})
i think it's relate to this line
itemsArray.push(inputTitle, inputAuthor, inputNumber)
// where
const inputTitle = document.getElementById("input-title")
const inputAuthor = document.getElementById("input-author")
const inputNumber = document.getElementById("input-number")
// should be below if you don't want printout [object Object]
itemsArray.push(inputTitle.value, inputAuthor.value, inputNumber.value)
why '[object Object]'
var array = []
var anchor = document.createElement('a')
array.push(JSON.stringify(anchor)) // -> ['{}']
var anchor2 = document.createElement('a')
anchor2.textContent = JSON.parse('{}')
anchor2.textContent // -> '[object Object]'

Trying to save all generated 'li' elements to local storage using JavaScript

This code successfully takes the contents of the form and saves it to an ordered list, 2 more functions do the same thing but instead create a timestamp. I'm trying to take every li element that gets generated and save it to localStorage when you push the save button and then repopulate it again from the local storage when you push the "load" button. I can't get it to work come hell or high water. The load button does nothing, and oddly enough the "save" button acts as a clear all and actually removes everything rather then saving it. Console log shows no errors. I have the JavaScript below and the corresponding HTML.
let item;
let text;
let newItem;
function todoList() {
item = document.getElementById("todoInput").value
text = document.createTextNode(item)
newItem = document.createElement("li")
newItem.onclick = function() {
this.parentNode.removeChild(this);
}
newItem.onmousemove = function() {
this.style.backgroundColor = "orange";
}
newItem.onmouseout = function() {
this.style.backgroundColor = "lightblue";
}
todoInput.onclick = function() {
this.value = ""
}
newItem.appendChild(text)
document.getElementById("todoList").appendChild(newItem)
};
function save() {
const fieldvalue = querySelectorAll('li').value;
localStorage.setItem('item', JSON.stringify(item));
}
function load() {
const storedvalue = JSON.parse(localStorage.getItem(item));
if (storedvalue) {
document.querySelectorAll('li').value = storedvalue;
}
}
<form id="todoForm">
<input id="todoInput" value="" size="15" placeholder="enter task here">
<button id="button" type="button" onClick="todoList()">Add task</button>
<button id="save" onclick="save()">Save</button>
<button id="load" onclick="load()">Load</button>
</form>
As #Phil and #Gary explained part of your problem is trying to use querySelectorAll('li') as if it would return a single value. You have to cycle through the array it returns.
Check the below code to give yourself a starting point. I had to rename some of your functions since they were causing me some errors.
<form id="todoForm">
<input id="todoInput" value="" size="15" placeholder="enter task here">
<button id="button" type="button" onClick="todoList()">Add task</button>
<button id="save" onclick="saveAll()" type="button">Save</button>
<button id="load" onclick="loadAll()" type="button">Load</button>
</form>
<div id="todoList"></div>
<script>
let item;
let text;
let newItem;
function todoList() {
item = document.getElementById("todoInput").value
text = document.createTextNode(item)
newItem = document.createElement("li")
newItem.onclick = function() {
this.parentNode.removeChild(this);
}
newItem.onmousemove = function() {
this.style.backgroundColor = "orange";
}
newItem.onmouseout = function() {
this.style.backgroundColor = "lightblue";
}
todoInput.onclick = function() {
this.value = ""
}
newItem.appendChild(text)
//Had to add the element
document.getElementById("todoList").appendChild(newItem);
}
function saveAll() {
//Create an array to store the li values
var toStorage = [];
var values = document.querySelectorAll('li');
//Cycle through the li array
for (var i = 0; i < values.length; i++) {
toStorage.push(values[i].innerHTML);
}
console.log(toStorage);
//CanĀ“t test this on stackoverflow se the jsFiddle link
localStorage.setItem('items', JSON.stringify(toStorage));
console.log(localStorage);
}
function loadAll() {
const storedvalue = JSON.parse(localStorage.getItem('items'));
console.log(storedvalue);
//Load your list here
}
</script>
Check https://jsfiddle.net/nbe18k2u/ to see it working

Clear or delete variable before declaring it again with javascript

I am VERY NEW to javascript and am messing around with some math. I currently have:
<input disabled="disabled" type="text" id="backer-prediction-answer" width="100" value="" />
<FORM>
<INPUT type="button" value="Apply" name="button1" onclick="apply()">
</FORM>
<script>
var backerPrediction1 = document.getElementById("backer-prediction-1").value;
var backerPrediction2 = document.getElementById("backer-prediction-2").value;
var backerPrediction3 = document.getElementById("backer-prediction-3").value;
var backerPrediction4 = document.getElementById("backer-prediction-4").value;
function apply(){
var backers = parseInt(backerPrediction1,10) + parseInt(backerPrediction2,10);
document.getElementById("backer-prediction-answer").value = (backers);
}
</script>
I would like to be able to hit apply and have it recalculate. Do I need to delete the variable before declaring it again? If so, how do I do that?
Move the variables backerPredictionX inside the function, so that they are evaluated everytime you apply()
<script>
function apply(){
var backerPrediction1 = document.getElementById("backer-prediction-1").value;
var backerPrediction2 = document.getElementById("backer-prediction-2").value;
var backers = parseInt(backerPrediction1,10) + parseInt(backerPrediction2,10);
document.getElementById("backer-prediction-answer").value = (backers);
}
</script>
With jquery (code not validated):
function apply(){
var backerPrediction1 = $("#backer-prediction-1").val();
var backerPrediction2 = $("#backer-prediction-2").val();
var backers = parseInt(backerPrediction1,10) + parseInt(backerPrediction2,10);
$("#backer-prediction-answer").val(backers);
}

how to add the input values in an array

i just like to ask regarding adding data in a array. But the data which i wanted to put is from a table of input boxes.. Here's the code that i've been practicing to get data:
http://jsfiddle.net/yajeig/4Nr9m/69/
I have an add button that everytime I click that button, it will store data in my_data variable.
i want to produce an output in my variable something like this:
my_data = [ {plank:"1",thickness:"4",width:"6",length:"8",qty:"1",brdFt:"16"}]
and if i would add another data again, it will add in that variable and it be something like this:
my_data = [ {plank:"1",thickness:"4",width:"6",length:"8",qty:"1",brdFt:"16"},
{plank:"2",thickness:"5",width:"6",length:"2",qty:"1",brdFt:"50"}]
the code that i have right now is really bad, so please help.
Currently my output:
1,4,6,4,1
You should be able to iterate over all of the textboxes using the following:
function add(e) {
var obj = {};
$('#addItem input[type="text"]')
.each(function(){obj[this.name] = this.value;});
myItems.push(obj);
}
Where myItems is a global container for your items and #addItem is your form.
Updated jsfiddle.
If you use a form and a submit button then you should be able to implement a non-JavaScript method to add your information so that the site will be accessible to people without JavaScript enabled.
Try this, sorry for modifying your form, but it works well:
HTML:
<form method="post" action="#" id="add_plank_form">
<p><label for="plank_number">Plank number</label>
<p><input type="text" name="plank_number" id="plank_number"/></p>
<p><label for="plank_width">Width</label>
<p><input type="text" name="plank_width" id="plank_width"/></p>
<p><label for="plank_length">Length</label>
<p><input type="text" name="plank_length" id="plank_length"/></p>
<p><label for="plank_thickness">Thickness</label>
<p><input type="text" name="plank_thickness" id="plank_thickness"/></p>
<p><label for="plank_quantity">Quantity</label>
<p><input type="text" name="plank_quantity" id="plank_quantity"/></p>
<p><input type="submit" value="Add"/>
</form>
<p id="add_plank_result"></p>
Javascript:
$(document).ready(function() {
var plank_data = Array();
$('#add_plank_form').submit(function() {
// Checking data
$('#add_plank_form input[type="text"]').each(function() {
if(isNaN(parseInt($(this).val()))) {
return false;
}
});
var added_data = Array();
added_data.push(parseInt($('#plank_number').val()));
added_data.push(parseInt($('#plank_width').val()));
added_data.push(parseInt($('#plank_length').val()));
added_data.push(parseInt($('#plank_thickness').val()));
added_data.push(parseInt($('#plank_quantity').val()));
$('#add_plank_form input[type="text"]').val('');
plank_data.push(added_data);
// alert(JSON.stringify(plank_data));
// compute L x W x F for each plank data
var computed_values = Array();
$('#add_plank_result').html('');
for(var i=0; i<plank_data.length; i++) {
computed_values.push(plank_data[i][1] * plank_data[i][2] * plank_data[i][3] / 12);
$('#add_plank_result').append('<input type="text" name="plank_add[]" value="' + computed_values[i] + '"/>');
}
return false;
});
});
Iterate through all keys, and add the values.
(code written from mind, not tested)
var added = { };
for (var i = 0; i < my_data.length; i ++) {
var json = my_data[i];
for (var key in json) {
if (json.hasOwnProperty(key)) {
if (key in added) {
added[key] += json[key];
} else {
added[key] = json[key];
}
}
}
}
You can use the javascript array push function :
var data = [{plank:"1",thickness:"4",width:"6",length:"8",qty:"1",brdFt:"16"}];
var to_add = [{plank:"2",thickness:"5",width:"6",length:"2",qty:"1",brdFt:"50"}];
data = data.concat(to_add);
Sorry I only glanced at the other solutions.
$(document).ready(function() {
var myData=[];
var myObject = {}
$("input").each(function() {
myObject[this.id]=this.value
});
alert(myObject["plank"])
myData.push(myObject)
});

Categories