Concat In JavaScript - javascript

For some reason the keyText variable isn't showing any value when it should concat for each variable in keywords.
When someone clicks the button it runs addKeyword and grabs the value of the input.
Tried to Console.Log the keyText variable and didn't work at all.
var keywords = [];
var keyText = "";
function addKeyword() {
var keywordName = document.getElementById("keywordAdd").value
keywords.push(keywordName);
keywords.forEach(showKeywords);
function showKeywords(item, index) {
var newString = "<span class='keyword' onclick='delKeyword(" + index + ")'>✖ " + item + "</span>";
keyText.concat(newString);
document.getElementById("keywords").innerHTML = keyText;
}
}
No Errors shown in Console. Expected result is a list of but doesn't show.

The problem is that .concat doesn't mutate the string, it returns a new string.
You need to do something like this:
keyText = keyText.concat(newString);
By the way, your current approach is not that efficient because it changes the element's inner HTML at each iteration. You should probably do that only once after the HTML for all the elements is generated. Here is another approach that does that:
const result = keywords.map((item, index) => (`<span class="keyword" onclick="delKeyword(${index})">✖ ${item}</span>`)).join('');
document.getElementById("keywords").innerHTML = result;

Titus answer is correct, but you can simply use :
keyText += newString;

Related

JavaScript loop through JSON data and print in html

I'm new to JavaScript and I'm trying to figure out how-to loop through JSON and print each selected value in HTML. My solution below does everything I want except print "all" rows of the JSON data. It only prints the last one. I've been researching on StackOverflow and elsewhere, but I'm not finding the solution. Sorry if this is a redundant question and thank you for your help!
//Fetch JSON from URL
//https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
fetch('https://s.codetasty.com/toddbenrud/sandBoxToddBenrud/example/songData.json')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
var songData = (JSON.stringify(myJson));
//https://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript
var index;
var obj = JSON.parse(songData);
for (index = 0; index < obj.length; ++index) {
var student_name = obj[index]['name'];
var student_email = obj[index]['email'];
var song_name = obj[index]['song'];
var song_url = obj[index]['url'];
document.getElementById("studentName").innerHTML = '<br>'+student_name;
document.getElementById("studentEmail").innerHTML = '<br>'+student_email;
document.getElementById("songTitle").innerHTML = '<br>'+song_name;
document.getElementById("songURL").innerHTML = '<br>'+song_url;
}
});
Inside your for loop you are reassigning your elements' content in every Iteration. It means that you fill your elements with the First item of the Array on the First time you run the for, but the Second time you run It, you replace the elements' content with the Second item of the Array. So you get only the Last Item Data.
To solve this problema, you should "increment" your element's content on each Iteration, instead of replace it. To achieve that, you replace the Lines like
document.getElementById("studentName").innerHTML = '<br>'+student_name;
With
document.getElementById("studentName").innerHTML += '<br>'+student_name;
The += operator does a concatenation on strings
Becasue you set string for elements, don't add string.
Replace from:
document.getElementById("studentName").innerHTML = '<br>'+student_name;
document.getElementById("studentEmail").innerHTML = '<br>'+student_email;
document.getElementById("songTitle").innerHTML = '<br>'+song_name;
document.getElementById("songURL").innerHTML = '<br>'+song_url;
To:
document.getElementById("studentName").innerHTML += '<br>'+student_name;
document.getElementById("studentEmail").innerHTML += '<br>'+student_email;
document.getElementById("songTitle").innerHTML += '<br>'+song_name;
document.getElementById("songURL").innerHTML += '<br>'+song_url;

each() with counter - const names

I am trying to loop through some HTML elements, extract the content and set them as a const value with the index number like this...
jQuery('.myitems').each(function (index) {
const myitem + index = [jQuery(this).text()];
console.log(myitem + index);
});
This is not working, can anyone tell me the correct way to achieve?
You can use object instead of count. And your code will be broken.
See the following solution.
jQuery('.myitems').each(function (index) {
const count = {}
count[myitem + index] = [jQuery(this).text()];
console.log(count[myitem + index]);
});
Shouldnt you store the values in an array instead?
const myitem = [];
jQuery('.myitems').each(function (index) {
myitem[index] = jQuery(this).text();
console.log(myitem[index]);
});
You cannot do what you're attempting in JS. An alternative would be to populate an array with the values by using map():
var arr = $('.myitems').map(function() {
return $(this).text();
}).get();
If you still want to use the 'myitem' + index prefix on the values then you could instead use an object:
var obj = {};
$('.myitems').each(function(i) {
obj['myitem' + i] = $(this).text();
});
Here, I have first set constant and then on looping I have set value with index number. Currenlty , I have made output on console. You can check it. Let me know if you do not understand
const staff=[];
$('.staff').each(function(index){
staff[index]=$(this).text();
})
console.log(staff);

How to print out the entries of a Map into an html document

Hi there I have the following code:
function showsaveobj(){
let patient = creatobj();
let befaktoren = patient.addfaktoren();
console.log(befaktoren);
let show = document.getElementById("show");
show.innerHTML = "Vorname: " + patient.vorname + "<br>Nachname: " + patient.nachname + "<br>" + (function() {for (let entry of befaktoren.entries()){return entry}})();
};
This last function is invoked when I press save inside the html document. It creates an object with a surname and a lastname and it has a method which creates a map out of the values the user has entered into the form. The form has 24 values corresponding to the 24h of the day. So the map is 24 entries long. I want to print these entries into the html document as you can see above. It works fine with the name and the surname but when I use the for..of loop to write the single entries It only prints out the first entry of the map.
When I add
for (let x of befaktoren.entries()){console.log(x);}
The console shows me 24 Arrays with the key and the value inside. When I do the same thing inside the string with innerHtml it only writes the first array of the map into the document.
I am doing something wrong here, but i cannot figure out what. After searching the web for several days now i hope someone here can help me.
Thanks in advance
I think you misunderstood the Map.entries() method. entries() does not return an iterable object that you can traverse with a for loop, but instead it returns an Iterator that contains all the entries which you can then retrieve with the next() method.
see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators
A Map itself is iterable so you can use your for loop on the map itself.
Despite that
your code:
someString + (function() {
for (let entry of befaktoren.entries()) {
return entry
}
})()
will always put the first element only into your string.
instead do something like this:
var befaktorenFormatter = function(input) {
let formattedString;
// directly iterate over the input iterable
for (let entry of input) {
formattedString += entry;
}
// don't return the current entry, return the fully formatted string instead
return formattedString;
}
show.innerHTML = "Vorname: " + patient.vorname + "<br>Nachname: " + patient.nachname + "<br>" + befaktorenFormatter(befaktoren);
Map has the convenience method forEach for iterating over its contents.
Also see: http://devdocs.io/javascript/global_objects/map/foreach .
Instead of using a for loop you could also do something like this:
let befaktoren = new Map([['foo', 'bar'], ['bar', 'foo']]);
let befaktorenFormatter = function(input) {
let formattedString;
input.forEach(function(value, key) {
formattedString += `${key}: ${value}<br>`;
});
return formattedString;
};
show.innerHTML = "Vorname: " + patient.vorname + "<br>Nachname: " + patient.nachname + "<br>" + befaktorenFormatter(befaktoren);
I hope that helped.

JS Object values start with 'undefined'

I am trying to use an array as a key value type scenario and it is working with the exception that every value starts with 'undefined'. I believe this is due to the initial assignment being a += operator however I am not sure how to resolve it.
This is the code stripped of a lot of string concats....
var phasehtml = {};
$.each(json, function (i, item) {
phasehtml[item.Phase] += 'item:'+item.ID;
});
Basically I am trying to append the string to the appropriate key....
You can change the code to only append the ID if there's already IDs:
var phasehtml = {};
$.each(json, function (i, item) {
// Use the existing value for the phase, or an empty string that we can append to
var existingValue = (phasehtml.hasOwnProperty(item.Phase) ? phasehtml[item.Phase] : "");
phasehtml[item.Phase] = existingValue + 'item:' + item.ID;
});
That's assuming that you want phasehtml to contain an appended lists of the form "item:1item:2" for each phase.
The array you have posted is empty.
var phasehtml = {};
It seems that is the cause the following statement
phasehtml[item.Phase]
is being evaluated to "undefined".
Hmmm,
got the problem.
In your code you are trying to add with that value which is previously not defined that's why this error is occur.
In your code you have not initialize the variable that you are adding.
So try this:
var phasehtml = {};
$.each(json, function (i, item) {
phasehtml[item.Phase] = "";
phasehtml[item.Phase] += 'item:'+item.ID;
});
In this first assign some value, here is blank and then use that index of array.

Use "event's" output as a variable

I have a problem to manipulate checkbox values. The ‘change’ event on checkboxes returns an object, in my case:
{"val1":"member","val2":"book","val3":"journal","val4":"new_member","val5":"cds"}
The above object needed to be transformed in order the search engine to consume it like:
{ member,book,journal,new_member,cds}
I have done that with the below code block:
var formcheckbox = this.getFormcheckbox();
formcheckbox.on('change', function(checkbox, value){
var arr=[];
for (var i in value) {
arr.push(value[i])
};
var wrd = new Array(arr);
var joinwrd = wrd.join(",");
var filter = '{' + joinwrd + '}';
//console.log(filter);
//Ext.Msg.alert('Output', '{' + joinwrd + '}');
});
The problem is that I want to the “change” event’s output (“var filter” that is producing the: { member,book,journal,new_member,cds}) to use it elsewhere. I tried to make the whole event a variable (var output = “the change event”) but it doesn’t work.
Maybe it is a silly question but I am a newbie and I need a little help.
Thank you in advance,
Tom
Just pass filter to the function that will use it. You'd have to call it from inside the change handler anyway if you wanted something to happen:
formcheckbox.on('change', function(cb, value){
//...
var filter = "{" + arr.join(",") + "}";
useFilter(filter);
});
function useFilter(filter){
// use the `filter` var here
}
You could make filter a global variable and use it where ever you need it.
// global variable for the search filter
var filter = null;
var formcheckbox = this.getFormcheckbox();
formcheckbox.on('change', function(checkbox, value){
var arr = [],
i,
max;
// the order of the keys isn't guaranteed to be the same in a for(... in ...) loop
// if the order matters (as it looks like) better get them one by one by there names
for (i = 0, max = 5; i <= max; i++) {
arr.push(value["val" + i]);
}
// save the value in a global variable
filter = "{" + arr.join(",") + "}";
console.log(filter);
});

Categories