So I save my array as a variable: var arrayContents = contentData;
and my array: ['content_1', 'content_2', 'content_3', 'content_4']
So i've got my array, I then want to place it into my HTML which i've done via using text like such: $('.container').text(arrayContents);
I need to break my text up so it currently looks like:
And i'm trying to get it to look like :
How can I break my array up so each item drops onto a new line? As when I use .text I print the whole array as one not each separate item.
Use a foreach loop and add a <br> tag to go to next line:
var contentToInsert;
$.each(arrayContents,function(value){
contentToInsert += value + "<br>";
});
$('.container').html(arrayContents);
You need to use html() instead of text(), check this
var htm = '';
var arrayContents = ['content_1','content_2','content_3'];
arrayContents.forEach(function(item){
htm += item + '<br />'; // break after each item
});
$('.container').html(htm);
Actually .text() works with a string value. You passed an array, which leads the "engine" to call arrayContents.toString() to get a string from the array. As you can see there, this function separates each entry by a comma.
If you want to produce an output on one column, you have to generate HTML (as shown in this answer), or editing the div object through javascript DOM functions (fiddle) :
for (var i = 0; i < arrayContents.length; i++) {
var currentElement = document.createElement("DIV"); // "DIV" or block-type element
var currentText = document.createTextNode(arrayContents[i]);
currentElement.appendChild(currentText);
document.getElementById("container").appendChild(currentElement);
}
Be sure of what kind of HTML you want to produce.
Related
So, I have an input, I enter words for filter answers.
My answers are my panel.
I create an Array for register my answers.
var array = [];
But when I finish my loop, I want to innerHTML my datas who are in my Array.
But I have a [object HTMLDivElement] because i push Object in Array.
Ok my question is = How can I create an Array Object and push my panel in
var obj = {}
And How can I display them
This code search in answer if the words exist
if (searchIndex > -1) {
If the answer exist , push the panel in my array and count how many answer he founds
array.push(panel);
countFound++;
}
When the loop is finish, exploit this data and display them
array1.forEach(function(element) {
// I dont know how is the method to exploit all data one by one
});
Depending on what your HTML looks like, you should use innerHTML attribute to get the contents of an element.
array.push(panel.innerHTML);
You get the object HTMLDivElement because that's what panel is.
If you want to iterate over the elements in array you can do it with a foor loop, alternative with a foreach loop, and to display it again in the HTML you once again need to use the innerHTML attribute.
text = "";
for (i=0; i < array.length; i++) {
text += array[I];
}
document.getElementById("result").innerHTML = text;
And of you want to repeat the procedure you need to empty the array variable afterwards:
array = []; // Add this line after appending your data to the HTML.
// Realistically after the for loop
For more Details go to adding-elements-to-object
Here is how it works:
var element = {}, cart = [];
element.id = 1;
element.panel = document.getElementById("panel");
cart.push(element);
alert(cart[0].panel);
<div id="panel"></div>
When I go to print out an array, That may have items put into it at later times, like this:
var ArrayEx = ['Zero'];
ArrayEx.push('One');
ArrayEx.push('Two');
alert(ArrayEx);
//or
document.write(ArrayEx);
It usually just prints it all out in one big blob of text. I was wondering, if I make it print in the alert box or the document, how i can make it a list, going down, or just with a , in between each one. Does anyone know how I could do that?
var ArrayEx = ['Zero'];
ArrayEx.push('One');
ArrayEx.push('Two');
var joined = ArrayEx.join(", ");
console.log(joined);
This will log
"Zero, One, Two"
Here's a quick and simple way to loop through an array and list the items in the array:
http://jsfiddle.net/mjgbm6c3/
HTML
<ul class="sample-list"></ul>
JS
var ArrayEx = ['Zero'];
ArrayEx.push('One');
ArrayEx.push('Two');
for(var i = 0; i < ArrayEx.length; i++){
var item = '<li>' + ArrayEx[i] + '</li>';
$('.sample-list').append(item);
}
Have a look at the Array.join() method, it will build a string out of the elements in the array and separate them with the string you pass to the separator parameter.
var ArrayEx = ['Zero'];
ArrayEx.push('One');
ArrayEx.push('Two');
alert(ArrayEx.join(', '));
// and
document.write(ArrayEx.join(', '));
// would both output: Zero, One, Two
For a new line, replace ', ' with '\n' in alerts and '<br />' in anything going to HTML; such as document.write().
document.write(ArrayEx.join('</br>'));
Im trying to add an array to a webpage. I have tried a few different pieces of code show below but none of them work. I would like the output to be similar to a list like:
text1
text2
text3
...
The code I have used so far is:
var i;
var test = new Array();
test[0] = "text1";
test[1] = "text2";
test[2] = "text3";
// first attempt
$('#here').html(test.join(' '));
// second attempt
$(document).ready(function() {
var testList="";
for (i=0;i<test.length; i++) {
testList+= test[i] + '<br />';
}
$('#here').html('testList');
songList="";
});
I am quite new to javaScript so I am not sure if I have just made a small mistake or if Im doing this in the wrong way. Also, above is a copy of all the code in my javaScript file and some places online are saying I need to import something? Im not sure!
Thanks
Try without quotes:
$('#here').html(testList);
-or-
$('#here').html(test.join('<br />'));
Another approach:
var html = ''; // string
$.each(test,function(i,val){ // loop through array
var newDiv = $('<div/>').html(val); // build a div around each value
html += $('<div>').append(newDiv.clone()).remove().html();
// get the html by
// 1. cloning the object
// 2. wrapping it
// 3. getting that html
// 4. then deleting the wrap
// courtesy of (http://jquery-howto.blogspot.com/2009/02/how-to-get-full-html-string-including.html)
});
$('#here').html(html);
There might be more code in the latter, but it'll be cleaner in the long run if you want to add IDs, classes, or other attributes. Just stick it in a function and amend the jQuery.
Try changing the line
$('#here').html('testList')
to
$('#here').html(testList)
What you have works if you remove the single quotes from testList. However, if you would like an actual unordered list you can do this. (here's a jsFiddle)
var test = new Array();
test[0] = "text1";
test[1] = "text2";
test[2] = "text3";
// first attempt
$('#here').html(test.join(' '));
// second attempt
$(document).ready(function() {
var testList=$("<ul></ul>");
for (var i=0;i<test.length; i++) {
$(testList).append($("<li></li>").text(test[i]));
}
$('#here').html(testList);
songList="";
});
This line:
$('#here').html('testList');
shouldn't have single quotes around testList - you want to use the content of the variable, not the string literal "testList".
Don't pass the variable as a string : $('#here').html('testList'); Pass it without quotes : $('#here').html(testList);
Here's the simplest version:
$(document).ready(function() {
var test = ["text1", "text2", "text3"];
$('#here').html(test.join("<br>"));
});
I need to get the text that is inside a element.
I can only grab the class of this element and NOT the ID.
<span class="fileName">test.png</span>
So I need a way to get test.png, but as you see I have only the class of the element and not the ID.
Just notice also that we may have more <span class="fileName"></span>, so it could look like this
<span class="fileName">test1.png</span>
<span class="fileName">test2.png</span>
<span class="fileName">test3.png</span>
<span class="fileName">test4.png</span>
In the case we have more, like the example above, I need to get ALL the values and not only one, because I need to pass this value to another page with jQuery. So it should be able to get one value or more from that element.
Please help!
And also I am not a javascript expert!
var filenames = $('.fileName').map(function(){
return $(this).text();
}).get();
The array filenames will contain all the names of the images. You can pass on this array to another jQuery function, or anywhere else you like to do so.
You can test it here »
Update
Since you request the filenames to be a string separated by a comma, you can do it like this:
var filenames = $('.fileName').map(function(){
return $(this).text();
}).get().join(',');
Now, filenames will contain the string test1.png,test2.png,test3.png,test4.png.
Use document.getElementsByClassName: http://jsfiddle.net/pCswS/.
var elems = document.getElementsByClassName("fileName");
var arr = [];
for(var i = 0; i < elems.length; i++) {
arr.push(elems[i].innerHTML);
}
alert(arr);
(Since you didn't tag the question with jQuery I assume you have to do it with plain JavaScript.)
$('span.fileName').each(function() {
var fileName = $(this).text();
doSomethingWithFileName(fileName);
});
Here the span.fileName selector returns all spans with class fileName then we iterate through, reading the text from each one. You may want to find a container element first and then only iterate inside that, e.g.
var $container = $('#myFileNames');
$container.find('span.fileName').each( ... );
Here's my take:
var spans = document.getElementsByClassName('fileName');
var values = [];
for(var i = 0; i < spans.length; i++) {
values.push(spans[i].innerHTML);
}
// Example of processing: alert the values
alert(values);
Use the following jQuery selector
$("span.fileName").html()
For example, I have such HTML:
<input name="someinput[]">
I made a function to clone/remove this input but now I want to assign indexes to name dynamically - when I make an element clones, its new names should be someinput[1], someinput[2] etc. - how to make this?
You could just replace [] with [index] using the attr callback:
var i = 0;
$('button').click(function(){
$('input:first').clone().attr('name',function(a,e){
i++;
return e.replace("[]","["+i+"]");
}).insertAfter($('input:last'));
});
example: http://jsfiddle.net/niklasvh/c9G7c/
Keep the index of the next input in a global variable, and then use that in your cloning function. Is that what you do?
var source = $('#source')
var copy = source.clone().attr('name', 'some[' + index + ']')
$('body').append(copy);