How to print a javascript array values in a jQuery .html() function? - javascript

I have a JavaScript array that contains a set of strings. I want to display them in a HTML div element by line by line using j Query or JavaScript.
My code is up to now:
var data = data;
for (i = 1; i <= data.length; i++) {
data[i] = data[i] + '<br />';
$(target).html('<a>'+data[i]+'</a>');
}
My data is displayed in this moment right now.
Labelling MachinesLabels - Plastic, Metal, Foil etcLabels FabricLaboratories - MedicalLaboratories - TestingLaboratory Equipment & SuppliesLaboratory Equipment Services & Calibration
I want them displayed like this as links (inside tags):
Labelling Machines
Labels - Plastic, Metal, Foil etc
Labels Fabric
Laboratories - MedicalLaboratories - Testing
Laboratory Equipment & Supplies
Laboratory Equipment Services & Calibration
Thanks in advance

You should add the breaks outside of the link tags and use .html() only once, as it completely replaces the innerHTML of the given element, i.e.
str = "";
for (i = 1; i <= data.length; i++) {
str += "<a>" + data[i] + "</a><br />";
}
$(target).html(str);
I would suggest another approach, to use innerHTML (javascript) or append (jquery) as another answer has already mentioned
for (i = 1; i <= data.length; i++) {
target.innerHTML += "<a>" + data[i] + "</a><br />";
}

Your code is incomplete here.Not sure if you have declare variable i anywhere in code.Also you are starting to loop from 1st index
Instead of appending to DOM on every iteration,create a string and concat the value to it. Append it on completion of the iteration.
var data = data,
htmlString="";
for (var i = 0; i <= data.length; i++) {
htmlString+= data[i] + '<br />';
}
$(target).append(htmlString);

The cleanest way will be wrapped in a div. And you need to use .append() method to not override the initial data that is already added to the target.
var data = ["Hello", "World", "Lorem", "Ipsum", "More length"];
for (var i = 0; i < data.length; i++) {
$("#result").append('<div>' + data[i] + '</div>');
}
.link {
color: #5ca5cc;
margin-bottom: 10px;
text-decoration: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
Clean and more simple code along with working demo.

Instead of a for/loop you could use ES6 in one line with map and a template literal.
$(target).html(arr.map(el => `<a>${el}</a><br/>`));
DEMO

var data = data;
var str = '';
for (var i = 1; i <= data.length; i++) {
str += `<a>${data[i]}<br /></a>`;
}
$(target).html(str);
Try this.

Related

Access array values inside json object

i get this with use of xmlhttprequest then i json.parse it and then for loop through the "resonse" to populate a list.
You can see in the next picture how the array in "response" looks when i click on "[0...99].
My problem is that the for loop doesnt populate the list tag in html, but when i try to write only for albania then it works. I need help with only javascript and not jQuery. you can see my code here:
The HTML part:
<section class="country">
<h3 id="countries"><br /></h3>
<nav id="countries2">
<ul id="countrylist"></ul>
</nav>
</section>
Here is javascript part:
var jsonData = JSON.parse(xhr.responseText);
document.getElementById("countrylist").innerHTML = "";
for (var i = 0; i < jsonData.response[i].length; i++) {
document.getElementById("countrylist").innerHTML += "<li id='" + jsonData.response[i].code + "'>" + jsonData.response[i].name + "</li>";
}
Here is the javascript part that works without foor loop:
document.getElementById("countrylist").innerHTML += "<li id='" + jsonData.response[0].code + "'>" + jsonData.response[0].name + "</li>";
Your for loop is ending early. Your condition is wrong.
What you have
for (var i = 0; i < jsonData.response[i].length; i++) {
What you should have
for (var i = 0; i < jsonData.response.length; i++) {
Your condition is against the length of the first element and is ending immediately.
Looking at your for loop condition:
for (var i = 0; i < jsonData.response[i].length; i++) {
jsonData.response[i].length is not the length of the array, but the length of one array element (in this case it is 1)! So your loop is only executing once.
You want instead to loop over all the array, like so:
for (var i = 0; i < jsonData.response.length; i++) {

Assigning an ID to a td within a JavaScript function

I have converted an xml file into a HTML table. The function I have used is here:
document.write("<table><tr><td>ALPHA</td><td>BRAVO</td><td>CHARLIE</td><td>DELTA</td><td>
ECHO</td><td>FOXTROT</td><td>GOLF</td><td>HOTEL</td></tr>");
var x = xmlDoc.getElementsByTagName("List");
for (i = 0; i < x.length; i++)
{
document.write("<tr><td>");
document.write(i) //populates the ALPHA column
document.write("</td><td>");
document.write(x[i].getElementsByTagName("BRAVOITEMS")[0].childNodes[0].nodeValue);
document.write("</td><td>")
document.write(x[i].getElementsByTagName("CHARLIEITEMS")[0].childNodes[0].nodeValue);
document.write("</td><td>");
document.write(x[i].getElementsByTagName("DELTAITEMS")[0].childNodes[0].nodeValue);
document.write("</td><td></td><td>");
document.write(x[i].getElementsByTagName("FOXTROTITEMS")[0].childNodes[0].nodeValue);
document.write("</td><td></td><td></td></tr>");
}
document.write("</table>")
The table presents exactly what I want and I plan to add the ECHOITEMS, GOLFITEMS and HOTELITEMS later.
My issue is, in order to progress any further, I need to assign IDs to each td above, so I can pull data from the table. I am able to assign an ID to a normal HTML td but I am struggling to so within the JavaScript code above. I need to add an ID to each td consisting of a short string followed by the i number. For example, using the first few lines of code above:
var x = xmlDoc.getElementsByTagName("List");
for (i = 0; i < x.length; i++)
{
document.write("<tr id='tdalpha'+ i><td>");
document.write(i)
document.write("</td><td id='tdbravo' + i>");
document.write(x[i].getElementsByTagName("BRAVOITEMS")[0].childNodes[0].nodeValue);
etc. Obviously the syntax isn't correct as when I try:
var test = document.getElementById('tdalpha24')
document.write(test)
I get an error message.
Any suggestions as to how to do this properly?!
you can do so like this -
for (i = 0; i < x.length; i++)
{
document.write('<tr id="tdalpha'+i'"><td>');
document.write(i)
document.write('</td><td id="tdbravo'+i+'">');
document.write(x[i].getElementsByTagName("BRAVOITEMS")[0].childNodes[0].nodeValue);
.....
As almost everybody before me noticed: "do not use document.write". In most cases it's considered bad technique.
And if you still want to use it, make one big string and use document.write only one time. It will increase perfomance. Just like this:
var str = '<table><tr><td>ALPHA</td><td>BRAVO</td><td>CHARLIE</td><td>DELTA</td><td>ECHO</td><td>FOXTROT</td><td>GOLF</td><td>HOTEL</td></tr>';
for (var i = 0; i < x.length; i++) {
str += '<tr id="tdalpha'+i'"><td>';
str += i;
str += '</td><td id="tdbravo'+i+'">';
str += x[i].getElementsByTagName("BRAVOITEMS")[0].childNodes[0].nodeValue);
str += '</td><td>';
str += x[i].getElementsByTagName("CHARLIEITEMS") [0].childNodes[0].nodeValue;
str += '</td><td>';
str += x[i].getElementsByTagName("DELTAITEMS")[0].childNodes[0].nodeValue;
str += '</td><td></td><td>';
str += x[i].getElementsByTagName("FOXTROTITEMS")[0].childNodes[0].nodeValue;
str += "</td><td></td><td></td></tr>";
}
str += '</table>';
document.write(str);
PS and your 'i' variable looks global to me.

Javascript loop not appending value in each container

This might be such a simple fix, but I think I've been stuck on this issue for way to long. Can someone spare a pair of eyes and see where I'm messing up?
I'm pulling data from a json file and trying to append the right value with the right container. Right now it's placing all the values in the first div container.
var metaDataArray = resultSet.searchResult[i].metadatatoshow;
for (var xx = 0; xx < metaDataArray.length; xx++) {
var metaDataContainer = "<div id='itemMetaDataContainer_"+xx+"'>Meta Data:" + metaDataArray[xx].name + "-</div>"
for (var xxx = 0; xxx < metaDataArray[xx].meta_values.length; xxx++) {
$('#itemMetaDataContainer_'+xx).append(metaDataArray[xx].meta_values[xxx]);
}
itemDetailsDiv.append(metaDataContainer);
}
you are trying to select a container before you append it to the details div. try appending the data values array to your container the following way:
var metaDataArray = resultSet.searchResult[i].metadatatoshow;
for (var xx = 0; xx < metaDataArray.length; xx++) {
var metaDataContainer = $("<div id='itemMetaDataContainer_" + xx + "'>Meta Data:" + metaDataArray[xx].name + "-</div>");
for (var xxx = 0; xxx < metaDataArray[xx].meta_values.length; xxx++) {
metaDataContainer.append(metaDataArray[xx].meta_values[xxx]);
}
itemDetailsDiv.append(metaDataContainer);
}
UPDATE:
a jQuery object holds the plain html element in index [0] (assuming its not an array).
to get the html out of metaDataContainer you can find it in metaDataContainer[0]
therefore, in order to append the jQuery object metaDataContainer to the plain html element itemDetailsDiv, you need to do the following:
itemDetailsDiv.innerHtml + = metaDataContainer[0];
UPDATE 2:
Here is a plain JavaScript solution:
var metaDataArray = resultSet.searchResult[i].metadatatoshow;
for (var xx = 0; xx < metaDataArray.length; xx++) {
//initializing the html string with the container opening tag and the description:
var metaDataContainer = "<div id='itemMetaDataContainer_" + xx + "'>Meta Data:" + metaDataArray[xx].name;
//looping through the values and adding them to the html string:
for (var xxx = 0; xxx < metaDataArray[xx].meta_values.length; xxx++) {
//create a span for each value and add it to the html string
metaDataContainer+="<span>" + metaDataArray[xx].meta_values[xxx] + "</span>";
//add a line break just for aesthetics, you can change to suit your formatting requirements
metaDataContainer+="<br/>";
}
//finish by adding a closing tag for the container
metaDataContainer+="-</div>"
//append the new html string to the details div
itemDetailsDiv.innerHtml +=metaDataContainer;
}

Dynamic class not being inserted when supposed to

Basically, I want to add a class to every list item, and each class has to be specific to a "house". So, I've created an array to store all the houses, and everything seems fine. The problem seems to be in the last for loop, where the classes are added, and their value are the ones store in the previous houseColours[] array: however, when I look in the console, the classes are not inserted.
Even more weird, if I manually insert a class in the console by doing something like this:
$('li:eq(0)').addClass(houseColours[0]);
... it works just fine. What could be the problem? Thanks.
function chart()
{
houseColours = [];
var html = "<ol start='0'>";
for (var i = 0; i < shuttle.seats.length; i++)
{
if (shuttle.seats[i] == null)
{
html += "<li>Empty Seat</li>";
}
else
{
for (var j = 0, n = PASSENGERS.length; j < n; j++)
{
if (shuttle.seats[i] == PASSENGERS[j].name)
{
var house = PASSENGERS[j].house;
break;
}
}
houseColours.push(house);
html += "<li>" + shuttle.seats[i] + ' at ' + house + "</li>";
}
}
html += "</ol>";
$("#chart").html(html);
for (var k = 0, banners = houseColours.length; k < banners; k++)
{
$('li:eq(k)').addClass(houseColours[k]);
}
}
In your selector, $('li:eq(k)') the k is part of the selector string, you should use it as a variable (outside of string), like below:
$('li:eq(' + k + ')').addClass(houseColours[k]);
It's better to use .eq method instead of :eq selector, however:
$('li').eq(k).addClass(houseColours[k]);

Search Box Function Not Eliminating Correct Value

I am trying to make a simple website where the user types input into a search box, and every time a key is press, their input is compared against the first row of a 2 dimensional array which checks for character matches. If the character they input doesn't match anything, I want it to remove that specific bucket of the array. I have attempted to write basic code for this I thought would work, and have it up at the demo site linked. (Sorry I am just using a free host and havn't optimized the equation table at all so bear with it)
http://fakefakebuzz.0fees.net/
As you can see, the function is not eliminating the appropriate table rows. For example, typing "A" should not eliminate the "Average Current Equation" row because the first letter of that is A, which means matches should not = 0.
I have been looking through this code all morning, and cannot find where I went wrong. I also want to stick to vanilla js.
Any help?
Thanks so much.
I just debugged your code, and the function you use is narrowTable. first remove onkeypress from body node
<body onload="printTable()" onkeypress="narrowTable()">
and add onkeyup instead to you input, like this:
<input type="search" name="equationSearch" id="equationSearch"
placeholder="Equation Search" autofocus="" onkeyup="narrowTable()">
because when you use onkeypress the key value hasn't been added to the input box and your input value has no value in your function, which is:
function narrowTable() {
var newTableContent = "";
var matches = 0;
var input = document.getElementById("equationSearch").value;
//input has no value
for (var i = 0; i < tableData.length; i++) {
for (var j = 0; j < tableData[i][0].length; j++) {
if (input == tableData[i][0].charAt(j)) {
matches++;
}
}
if (matches == 0) {
tableData.splice(i, 1);
}
matches = 0;
}
for (var i = 0; i < tableData.length; i++) {
newTableContent += "<tr><td>" + tableData[i][0] + "</td><td>" + tableData[i][1] + "</td></tr>";
}
document.getElementById("table").innerHTML = newTableContent;
}
the other problem your code has is after printing your table, your tableData variable has changed because you have removed some of indexes. you should reset the tableData to its original value or you can do:
function narrowTable() {
//create a copy of your original array and use currenttableData instead
var currenttableData = tableData.slice();
var newTableContent = "";
var matches = 0;
//your code
}
the other problem here is the way you search for your input value:
for (var j = 0; j < tableData[i][0].length; j++) {
if (input == tableData[i][0].charAt(j)) {
matches++;
}
}
if (matches == 0) {
tableData.splice(i, 1);
}
you can easily do this, instead:
if(tableData[i][0].search("input") == -1){
tableData.splice(i, 1);
}
First, to check if a string is a substring of another string, you can use indexOf. It will return -1 if the string is not found in the other string.
Second, you shouldn't alter the array while you are still looping through it, unless you make sure to alter the counter variable (i in this case) appropriately.
var dataToRemove = [],
i;
for (i=0; i<tableData.length; i++) {
if(tableData[i][0].indexOf(input) == -1) {
// add the index to the to-be-removed array
dataToRemove.push(i);
}
// remove them in reverse order, so the indices don't get shifted as the array gets smaller
for(i = dataToRemove.length - 1; i >= 0; i--) {
tableData.splice(i, 1);
}
dataToRemove = [];
for (i=0; i<tableData.length; i++) {
newTableContent += "<tr><td>" + tableData[i][0] + "</td><td>" + tableData[i][1] + "</td></tr>";
}
I haven't tested this code, but it should at least give you a better idea of how to make this work.

Categories

Resources