Possible to display an Array with for loop and InnerHTML? - javascript

I just wanted to display my Array inside of either an div or a heading.
The code i posted down below only displays the last part of the "List".
When i tried to use: document.write instead, everything worked fine.
Is there any special trick to display the list the same way document.write does using my Code below?
var Users = ["Till", "Didi", "Klausi", "Heinz"];
for (var i = 0; i < Users.length; i++) {
document.querySelector("div").innerHTML = Users[i] + " is always on my page " + "<br>";
}

Build the whole HTML first by iterating on the array and concatenating strings. And then set it as innerHTML of the div.
var Users = ["Till", "Didi", "Klausi", "Heinz"];
var _html = "";
for (var i = 0; i < Users.length; i++) {
_html += Users[i] + " is always on my page " + "<br>";
}
document.querySelector("div").innerHTML = _html;
<div></div>

Every time the loop runs it inserts the current iterable item into the HTML, replacing the one previous. So add a variable outside of the loop and append to it using var x += User[i].

var separator = ' is always on my page<br>';
var html = Users.join(separator) + separator;
document.querySelector("div").innerHTML = html;
// writes
// "Till is always on my page<br>Didi is always on my page<br>Klausi is always on my page<br>Heinz is always on my page<br>"

Related

chosen-select mutliple select update from an array

I'm using the chosen plugin for a multiple select. I want to retrieve the customer pre-selected values from the database and display them in the multiple select when i return the rest of the data.
The following code works fine:
$('.chosen-select').val(["Test1", "Test2"]).trigger('chosen:updated');
However when I try and put a variable in there like below, it doesn't populate the values.
$('.chosen-select').val([res]).trigger('chosen:updated');
I've pulled the data out and I then loop through the array and store it in a variable. I've checked the contents of the res variable and it's correct, so now I'd like to reference it within the square brackets but it doesn't work, and it doesn't throw any errors. Any help would be much appreciated!
var i;
var res = "";
for (i = 0; i < array.length; i++) {
array[i] = $.trim(array[i]);
var buildValue2 = '"' + array[i] + '", ';
if (i == array.length - 1) {
/* this is the last one so no comma*/
buildValue2 = '"' + array[i] + '"';
}
res = res.concat(buildValue2);
}
alert(res);
$('.chosen-select').val([res]).trigger('chosen:updated');

Looking for a way to break up a string with multiple \n and turn it into innerHTML

I have been writing JavaScript since yesterday and am brand new at it.
I have a string that I am breaking up and turning into input for a table. The entries are separated by '\n' like 'a\nb', which indicates the need for a new row between a and b.
The current code that I have works for a single instance of '\n', but it quit working when it was back to back entries, specifically "1.1\n2.1\n3.1\n4.1\n".
It has worked with other examples that are comma separated, such as "a,b,c\n1,2,3", "1.1,1.2,1.3,1.4,1.5\n", and "1.1,1.2,1.3,1.4,1.5\n2.1,2.2,2.3,2.4,2.5\n3.1,3.2,3.3,3.4,3.5\n4.1,4.2,4.3,4.4,4.5\n". Because some inputs are comma separated, it must work with those as well as with the input that is separated by '\n'.
My method up to this point has been to split the string into an array, and then search the index of the array to see if it contains the '\n'. If it does, I split the array at the '\n', and splice it with two entries instead of one. I then set a variable indicating that I need to go to the next row, which moves into an if else if right below.
var functionCreate = function (strInput) {
var array = strInput.split(",");
var html = "<table border=1><tr>";
for (var i = 0; i < array.length; i++) {
var newL = false;
if (array[i].indexOf("\n") >= 0) {
newL = true;
newStr = array[i].split("\n");
array.splice(i, 1, newStr[0]);
array.splice(i + 1, 0, newStr[1]);
}
if (newL === true) {
html += "<td>" + array[i] + "</td></tr>";
}
else if (array[i]) {
html += "<td>" + array[i] + "</td>"
}
}
html += "</table>"
document.getElementById('output').innerHTML = html;
What I output currently is:
output: "<table border=\"1\"><tbody><tr><td>1.1</td></tr><tr><td>2.1</td></tr></tbody></table>"
And my expected is:
"<table border=\"1\"><tbody><tr><td>1.1</td></tr><tr><td>2.1</td></tr><tr><td>3.1</td></tr><tr><td>4.1</td></tr></tbody></table>"
The 3.1 and 4.1 are getting cut off, which is understandable because I believe everything trailing the 2.1 is in i + 1 of newStr.
Does anyone have any idea how to get past this? Is there a way to split it at only the first '\n' and run the through the loop again until there are no more newlines?
Change
var array = strInput.split(",");
to
var array = strInput.split("\n");

Is it possible to use a value from within a 'for' loop outside of the actual loop cycle?

I have a for loop that cycles through my array and prints to the console each value that meets a certain condition. I would like to take these values and insert them into variables outside the loop. Is this possible?
for (var i = 0; i < myArray.length; i++) {
if (myArray[i].catType === 'I') {
console.log(myArray[i].location);
}
...
}
I'd like to insert whatever is outputted from the for loop in a tooltip object that sits outside of this for loop.
var header = "<thead>" +
"<tr>" +
"<td class='legend-color-guide'><div style='background-color: " + series.color + ";'></div></td>" +
"<td class='key'><strong>" + <INSERT HERE> + "</strong></td>" +
"</tr>" +
"</thead>";
How can this be done?
Create an array, add the new value each time the condition is meet.
var arr = [];// initialize array
for (var i = 0; i < myArray.length; i++) {
if (myArray[i].catType === 'I') {
console.log(myArray[i].location);
arr.push("Add Whatever Here");// append new value to the array
}
}
This is possible, but you don't (and shouldn't) want to use the output from the console. Instead, you want to append the values to a variable, and then set the header variable. Like: (I've used another example)
var putIn = "";
for (i = 0; i < array.length; i++) {
if (array[i] === x) {
putIn += array[i].property;
console.log(array[i].property);
}
}
var final = "on the left side " + putIn + " on the right side";
As you can see, I've put the values in the string and logged the elements in the array separately. There's no need to use the log values as values to insert into the string.
Define a global variable. Then set that variable in your loop cycle. Or create an array and push each value from your loop into the array, then you can access them from something else.

javascript replace string/html from array

I try to create a system replacement for ToolTip.
I already create a version but its not quite optimal (search a better way to do it)
here's a fiddle : http://jsfiddle.net/forX/Lwgrug24/
I create a dictionary (array[key]->value). the array is order by length of the key.
each key is a word or an expression, the value is the definition of the expression.
So, I replace the expression by a span (could/should be a div). The span is used for the tooltip (I use the data-title as tooltip text).
because some word is reused in expression, I need to remove expression already with tooltip (in real life think of father/grandfather, you dont want the definition of father inside grandfather). For replacement I use a ramdom value. That's the worst of this code.
You could make comment or post a new way to do it. maybe someone already did it.
Clarification :
I think my way to do it is wrong by using a string for replacement. Or it could be more secure. How should I do it?
html :
<div class="container">
one two three four five six seven eight nine ten
</div>
javascript :
$(function() {
var list = [
{'k':'one two three four five','v':'First five number.'},
{'k':'four five six seven','v':'middle number.'},
{'k':'six seven eight','v':'second middle number.'},
{'k':'two','v':'number two.'},
{'k':'six','v':'number six.'},
{'k':'ten','v':'number ten.'}
];
$(".container").each(function(){
var replacement = new Array();
for (i = 0; i < list.length; i++) {
var val = list[i];
var rString = randomString(32, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
replacement[rString + "_k"] = htmlEncode(val["k"]);
replacement[rString + "_v"] = htmlEncode(val["v"]);
var re = new RegExp("(" + val["k"] + ")","g");
$(":contains('" + val["k"] + "')",$(this).parent()).html(function(_, html) {
var newItem = '<span class="itemWithDescription" '
+ 'data-title="' + rString + "_v" + '">'
+ rString + "_k"
+ '</span>';
return html.replace(re, newItem);
});
}
for (var k in replacement){
$(this).html($(this).html().replace(k,replacement[k]));
console.log("Key is " + k + ", value is : " + replacement[k]);
}
});
$(document).tooltip({
items:'.itemWithDescription',
tooltipClass:'Tip',
content: function(){
var title = $(this).attr("data-title");
if (title == ""){
title = $(this).attr("title"); //custom tooltips
}
return title;
}
});
});
function randomString(length, chars) {
var result = '';
for (var i = length; i > 0; --i) result += chars[Math.round(Math.random() * (chars.length - 1))];
return result;
}
function htmlEncode(value){
//create a in-memory div, set it's inner text(which jQuery automatically encodes)
//then grab the encoded contents back out. The div never exists on the page.
return $('<div/>').text(value).html();
}
I added a little thing. on the random function, I put a | and } for every char, its bigger but there's not much chance to have a conflic with an expression.
for (var i = length; i > 0; --i) result += '|' + ( chars[Math.round(Math.random() * (chars.length - 1))] ) + '}' ;
http://jsfiddle.net/forX/Lwgrug24/3/

translate a variable amount of input values into a select

var namelist = editnamebox.children.value;
for (var f = 0; f < namelist.length; f += 1) {
slotname.innerHTML = '<optgroup><option>' + namelist[f] + '</option></optgroup>';
}
editnamebox is a div containing avariable number of inputs I want to generate a with the value of each editnamebox input as an option.
The code above does no work, I also tried namelist[f].value instead of in the namelist var which also does not run. What is wrong here?
Full page: http://powerpoint.azurewebsites.net/
Set a timeslot. "Undefined" should be the content of the empty text fields above
You should build the string with the loop and then update the innerHTML. (Assuming other portions are correct without seeing your markup)
var namelist = editnamebox.children,
slotnameHtml = '';
//build html string
for (var f = 0; f < namelist.length; f += 1) {
slotnameHtml += '<optgroup><option>'
+ namelist[f].value
+ '</option></optgroup>';
}
slotname.innerHTML = slotnameHtml; //update html

Categories