Add to element as divs - javascript

Okay, so here's my code:
HTML:
<h2>Header</h2>
<div id="results1" class="results">
<h1>Results 1</h1>
</div>
JS:
(function() {
var results = document.getElementById('results1');
var drink = [ 'Rum', 'Vodka', 'Whiskey', 'Beer' ];
})();
I need to add the drinks to the results element as divs.

Just a simple for loop to iterate over the array, and then append each item to the results div.
for (var i = 0 ; i < fruit.length; i++) {
results.innerHTML += "<div>" + fruit[i] + "</div>";
};
JSFiddle Demo

With pure JavaScript:
(function() {
var results = document.getElementById('results1');
var fruits = [ 'Rum', 'Vodka', 'Whiskey', 'Beer' ];
for(var i = 0; i < fruits.length; i++){
var fruit = document.createElement('div').innerHTML = fruits[i];
results.appendChild(fruit);
}
})();

Demo
try like this
var parent = $("#results1");
var fruit = ['Rum', 'Vodka', 'Whiskey', 'Beer'];
$.each(fruit, function (i, val) {
parent.append("<div id=" + val + " >" + val + "</div>");
});

You can use this:
js
(function() {
var results = document.getElementById('results1');
var fruit = [ 'Rum', 'Vodka', 'Whiskey', 'Beer' ];
for(var i=0; i<fruit.length; i++){
var div = $("<div>" + fruit[i] + "</div>");
$(div).appendTo("#results1");
}
})();
fiddle

(function() {
var results = document.getElementById('results1');
var fruit = [ 'Rum', 'Vodka', 'Whiskey', 'Beer' ];
for(var i=0; i<fruit.length;i++){
$("#results1").append('<div>'+fruit[i]+'</div>');
}
})();

fruit.forEach(function(value,index){
var div = document.createElement('div');
div.innerHTML = value;
$("#results1").append(div);
});

You may try this one:
(function() {
var results = document.getElementById('results1');
var drink = [ 'Rum', 'Vodka', 'Whiskey', 'Beer' ];
results.innerHTML += '<div>' + drink.join('</div><div>') + '</div>';
})();

This is the for loop you could use for javascript
and incorporated it into your html.
var drink = ["Rum", "Vodka", "Whiskey", "Beer"];
for (index = 0; index < drink.length; ++index) {
text += drink[index];
}

Related

Can't loop over array; each item works individually

The following piece of code works as expected:
var slctr = "What's new";
var section = document.querySelector('[aria-label="'+slctr +'"]');
var sectionAs = section.querySelectorAll('a');
$(sectionAs).click(function(e){
e.preventDefault();
var t = $(e.target).text();
var sectionTitle = section.getAttribute('aria-label');
alert('Title: ' + sectionTitle+', text: ' + t);
return false;
});
If I try to apply this to every {{section}}, the working stops:
var sections = [
"What's new",
"What's newish",
"What's not new at all"
];
for(var l = 0; l < sections.length; l++){
var slctr = sections[i];
var section = document.querySelector('[aria-label="'+slctr +'"]');
var sectionAs = section.querySelectorAll('a');
$(sectionAs).click(function(e){
e.preventDefault();
var t = $(e.target).text();
var sectionTitle = section.getAttribute('aria-label');
alert('Title: ' + sectionTitle + ', text: ' + t);
return false;
});
}
Why does it not work for the loop?
You need to use closures or IIFEs as you are setting some event handlers, which are some times asynchronous. You just need to update your code like:
var sections = [
"What's new",
"What's newish",
"What's not new at all"
];
for (var i = 0; i < sections.length; i++) {
(function (i) {
var slctr = sections[i];
var section = document.querySelector('[aria-label="' + slctr + '"]');
var sectionAs = section.querySelectorAll('a');
$(sectionAs).click(function(e) {
e.preventDefault();
var t = $(e.target).text();
var sectionTitle = section.getAttribute('aria-label');
alert('Title: ' + sectionTitle + ', text: ' + t);
return false;
});
})(i);
}
And one more thing is that you have used i for index and l for loop.
You use l as loop variable but then trying to access sections[i] and i is not defined
var slctr = sections[l];

Loop using two related arrays

When a button is clicked i want the results in the array to be listed for example: John Smith 16, Jack Snow 10 etc..
I want to use a loop however the code in my loop is incorrect at the moment as when i click the button all i get is: [object Object].
Can someone provide a possible fix?
function begin() {
listresults();
();
}
var results1 = {name:"John Smith", score:16};
var results2 = {name:"Jack Sow", score:10};
var results3 = {name:"Tessa Flip", score:15};
var results = [results1, results2, results3];
function listresults() {
var text = "";
var total = 0;
var i;
for (i in results) {
text += results[i] + "<br>";
}
document.getElementById('message').innerHTML = text;
}
I would first check that the lengths of the 2 arrays are the same. Then iterate using a for loop:
final int timeLength = TIME.length;
if (timeLength != stat.size()) {
//something may not be right
}
for (int i = 0; i < timeLength; i++) {
System.out.println(time[i]+" "+stat.get(i));
}
You are pushing objects results1, results2, etc in the array 'results'.
So while iterating the array you should access the object properties as shown below:
function listresults() {
var text = "";
var total = 0;
var i;
for (i in results) {
text += results[i]['name'] + ' ' + results[i]['score'] + "<br>";
}
As you are appending objects instead of object values in the filed.
This is the proper way of accessing name and score from object which is returned when you are looping through your array of objects :
function begin() {
listresults();
();
}
var results1 = {name:"John Smith", score:16};
var results2 = {name:"Jack Sow", score:10};
var results3 = {name:"Tessa Flip", score:15};
var results = [results1, results2, results3];
function listresults() {
var text = "";
var total = 0;
for (var i=0; i < results.length; i++) {
text += results[i].name + " " + results[i].score + "<br>";
}
document.getElementById('message').innerHTML = text;
}
Here is an Jsfiddle example
Recommend you to use Array methods(map, join) instead of pure loops
function begin() {
listresults();
}
var results1 = {name:"John Smith", score:16};
var results2 = {name:"Jack Sow", score:10};
var results3 = {name:"Tessa Flip", score:15};
var results = [results1, results2, results3];
function listresults() {
document.getElementById('message').innerHTML =
results.map(function(item) {
return item.name + ' ' + item.score;
}).join('<br>');
document.getElementById('total').innerHTML =
results.map(function(item) {
return item.score;
}).reduce(function(sum, score) {
return sum + score;
}, 0);
}
<button onclick="begin()">begin</button>
<br />
<div id="message"></div>
<div>total: <span id="total">0</span></div>
Use Array.map() and Array.join()
var results1 = {name:"John Smith", score:16};
var results2 = {name:"Jack Sow", score:10};
var results3 = {name:"Tessa Flip", score:15};
var results = [results1, results2, results3];
var res = results.map(item => { return item.name+ " " +item.score });
console.log(res.join(", "));

Making array from user input (Seperated by linebreaks) with Javascript

I am trying to take user input in form of a lot of strings. I want to store them in an array, and the input should be seperated by line breaks.
It should be very much like this: https://www.random.org/lists/
I can not grasp where to being - can someone help? I am using JavaScript but any solutions using JS or jQuery would be great!
I have posted my JS. I want the var people from user input, instead of having to populate the array myself.
Thanks,
$(document).ready(function() {
$(".btn").on('click', function() {
var people = ["Markus Eriksson", "Leticia Hoshino", "Yemi Afolabi", "Eskil Fogelström", "Josefina Liedberg", "David Bjørn Bograd", "Tilda Dahlgren", "Damien Vignol", "Sofie Cousu", "Carolina Lindelöw", "Bilal Khan", "Louise Brandrup-Wognsen", "Emilia Lehto", "Albin Hagström",
"Victor Borg", "Anna Stella Lo-Ré", "Loucmane", "Angelica Ruth", "Victoria VL", "Johan Hellström", "Micke Skoglund", "Anna Unger", "Isaac Sennerholt", "Cyndie Léa Vintilescu", "Mahle Rakela Robin", "Louise Ek", "Ibrahim Bajwa", "Abodi Ismail",
"Alex Ashman", "Elin Grass Casalini", "Amanda Schultz", "Abenezer Abebe", "Julia Hoff", "Enny Hellsén", "Michel George", "Abdullahi Hussein", "Teodor Meurling", "Andrea Sami Mogren", "Thea Arpine Gasparyan", "Jakob Eberson"
];
var groupSize = $("input[name=checkListItem]").val();
var groups = [];
$(".group").remove();
// Randomizing function
Array.prototype.shuffle = function() {
var input = this;
for (var i = input.length - 1; i >= 0; i--) {
var randomIndex = Math.floor(Math.random() * (i + 1));
var itemAtIndex = input[randomIndex];
input[randomIndex] = input[i];
input[i] = itemAtIndex;
}
return input;
};
people.shuffle();
// Split people into chunks and push new arrays into var groups
while (people.length > 0) {
chunks = people.splice(0, groupSize);
var chunksSpace = chunks.join(', ');
groups.push(chunksSpace);
}
// Append the groups into the DOM
$(document).ready(function() {
for (var i = 0; i < groups.length; i++) {
$('.all-groups').append("<div class='group'><p><span class='groupheader'>Group " + (i + 1) + "</span></br> " + groups[i] + "</p></div>");
}
});
});
});
Pure Javascript
document.getElementById("element_id").value.split("\n");
OR JQuery $("#element_id").val().split("\n");
For your example give your input id='people' and should work, also avoid extra line breaks by .replace(/\n+/g,"\n").
$(document).ready(function() {
// Randomizing function
Array.prototype.shuffle = function() {
var input = this;
for (var i = input.length - 1; i >= 0; i--) {
var randomIndex = Math.floor(Math.random() * (i + 1));
var itemAtIndex = input[randomIndex];
input[randomIndex] = input[i];
input[i] = itemAtIndex;
}
return input;
};
$(".btn").on('click', function() {
var people = $("#people").val().replace(/\n+/g,"\n").split("\n");
var groupSize = $("input[name=checkListItem]").val();
var groups = [];
$(".group").remove();
people.shuffle();
// Split people into chunks and push new arrays into var groups
while (people.length > 0) {
chunks = people.splice(0, groupSize);
var chunksSpace = chunks.join(', ');
groups.push(chunksSpace);
}
// Append the groups into the DOM
$(document).ready(function() {
for (var i = 0; i < groups.length; i++) {
$('.all-groups').append("<div class='group'><p><span class='groupheader'>Group " + (i + 1) + "</span></br> " + groups[i] + "</p></div>");
}
});
});
});
var text = $('#total-number').text();
var eachLine = text.split('\n');
alert('Lines found: ' + eachLine.length);
for(var i = 0, l = eachLine.length; i < l; i++) {
alert('Line ' + (i+1) + ': ' + eachLine[i]);
}
Use split to split a multi line string into parts:
var textarea = document.querySelector("textarea");
textarea.addEventListener("change", function(e) {
console.log(textarea.value.split((/[\n\r]/g)));
});
<textarea></textarea>
Regex links:
\r
\n

Comma separated values: from strings to objects to list

I have 3 variables with strings containing comma separated values (I don't know how many) which I want to combine into jQuery objects.
"name1,name2,name3,nameN"
"value1,value2,value3,valueN"
"id1,id2,id3,idN"
to:
var item1 = { name: name1, value: value1, id: id1 };
var item2 = { name: name2, value: value2, id: id2 };
var item3 = { name: name3, value: value3, id: id3 };
var itemN = { name: nameN, value: valueN, id: idN };
To then iterate an operation over each item, for example to append a list:
<h3>items</h3>
<ul>
<li>item1</li>
<ul>
<li>value: <b>value1</b></li>
<li>id: <b>id1</b></li>
</ul>
[...]
<li>itemN</li>
<ul>
<li>value: <b>valueN</b></li>
<li>id: <b>idN</b></li>
</ul>
<ul>
What is the best way to do this?
You can build an array of your items like this:
var names = "name1,name2,name3,nameN";
var values = "value1,value2,value3,valueN";
var ids = "id1,id2,id3,idN";
var namesArray = names.split(",");
var valuesArray = values.split(",");
var idsArray = ids.split(",");
var item, items = [];
for (var i = 0; i < namesArray.length; i++) {
item = {};
item.name = namesArray[i];
item.value = valuesArray[i];
item.id = idsArray[i];
items.push(item);
}
Then, to build the HTML from that, you can do this:
var main = $("<ul>");
var str = "";
for (var i = 0; i < items.length; i++) {
str += "<li>" + items[i].name + "</li><ul><li>value: <b>" + items[i].value + "</b></li>";
str += "<li>id: <b>" + items[i].id + "</b></li></ul>";
}
main.html(str);
$(document.body).append("<h3>items</h3>")
$(document.body).append(main);
You can see it work here: http://jsfiddle.net/jfriend00/yWU3L/4/.
You may want to use the DOM for this.
Using innerHTML means having in-line HTML in your javascript. This breaks Seperations of concerns and leads to maintenance hell.
Live Example
var createListFragment = (function () {
function createItems(names,value,ids) {
var namesArray = names.split(",");
var valuesArray = value.split(",");
var idsArray = ids.split(",");
return namesArray.map(function (name, key) {
return {
name: name,
value: valuesArray[key],
id: idsArray[key]
}
});
}
function createLi(item) {
var itemLi = document.createElement("li");
itemLi.textContent = item.name;
var propertiesUl = document.createElement("ul");
itemLi.appendChild(propertiesUl);
var valueLi = document.createElement("li");
valueLi.appendChild(document.createTextNode("value: "));
var b = document.createElement("b");
b.textContent = item.value;
valueLi.appendChild(b);
propertiesUl.appendChild(valueLi);
var idLi = document.createElement("li");
idLi.appendChild(document.createTextNode("id: "));
var b = document.createElement("b");
b.textContent = item.id;
idLi.appendChild(b);
propertiesUl.appendChild(idLi);
return itemLi;
}
function createListFragment(names, values, ids) {
var items = createItems(names, values, ids);
var fragment = document.createDocumentFragment();
var h3 = document.createElement("h3");
h3.textContent = "items";
fragment.appendChild(h3);
var ul = document.createElement("ul");
fragment.appendChild(ul);
items.forEach(function (item) {
var li = createLi(item);
ul.appendChild(li);
});
return fragment;
}
return createListFragment;
})();
You may need a DOM-shim and ES5-shim for cross browser compliance.

JQGrid MultiSelect getting the column data

Is there a way for the JQGrid to return an array of column Data for using multiSelect as opposed to just an array of rowIds ?
At the moment I can only return the last column data that was selected.
jQuery("#buttonSelected").click(function() {
var ids = jQuery("#relatedSearchGrid").getGridParam('selarrrow');
var count = ids.length;
for (var i = 0; i < count; i++) {
var columnData = $("#relatedSearchGrid").find("tbody")[0].rows[$("#relatedSearchGrid").getGridParam('selrow') - 1].cells[1].innerHTML;
alert("In the loop and " + columnData );
}
if (count == 0) return;
var posturl = '<%= ResolveUrl("~") %>Rel******/AddSelected****/' + ids;
if (confirm("Add these " + count + " Docs?")) {
$.post(posturl,
{ ids: columnData },
function() { jQuery("#relatedSearchGrid").trigger("reloadGrid") },
"json");
}
})
Use getRowData to get the data for each row:
var rowData = $("#relatedSearchGrid").getRowData(ids[i]);
var colData = rowData.Name_Of_Your_Column;
var userListjqGrid = $('#UserListGrid'),
selRowId = userListjqGrid.jqGrid('getGridParam', 'selrow'),
userId = userListjqGrid.jqGrid('getCell', selRowId, 'UserId'),
userName = userListjqGrid.jqGrid('getCell', selRowId, 'UserName'),
subIds = $(subgridTableId).getGridParam('selarrrow'),
accessRuleIds = [];
for (var i = 0; i < subIds.length; i++) {
accessRuleIds[i] = $(subgridTableId).getRowData(subIds[i]).AccessRuleId;
}

Categories