Inserting custom text in JS output - javascript

I have below line in my js code. i runs from 0 to 2. I want to put a custom text in place of: ' + info[i] + ' for each of the i's(over iterations of i). How do I do that?
for(var i=0; i < origins.length-1; i++) {
var results = response.rows[i].elements;
output += '<tr><td>' + info[i] + '</td><td>' + origins[i] + '</td><td></td><td>' + destinations[i+1] + '</td><td></td><td>' + results[i+1].distance.text + '</td></tr>';
}

. I want to put a custom text in place of: ' + info[i] + ' for each of the i's(over iterations of i).
Not sure what is "custom text" but assume your custom text should be in an array:
var customText = ["Custom text for i=0",
"Custom text for i=1",
"Custom text for i=2"];
for(var i=0; i < origins.length-1; i++) {
var results = response.rows[i].elements;
output += '<tr><td>' + customText[i] + '</td><td>' + //....
}
Also how to align the out-put of the code at the center of my webpage?
This is connected to CSS rather than with JS. Use CSS property text-align: center for a table, div or wharever you want to center.

If the custom text isn't in a variable, just put it directly into the HTML that you're generating:
output += '<tr><td>Custom Text</td><td>' + origins[i] + '</td><td></td><td>' + destinations[i+1] + '</td><td></td><td>' + results[i+1].distance.text + '</td></tr>';

Related

How to change span ID with each span created in loop

I have the following piece of code:
compareHtml += " </tr><tr>";
for (i = 0; i < compareArr.length; i++) {
compareHtml += '<td>' + compareArr[i].journaltitle + '</td>';
journalTitle.append('<span>' + compareArr[i].journaltitle + '</span> ');
}
And it creates a new span for each journalTitle. However, I want each new span to be created to have the ID "journalTitle1" "journalTitle2" "journalTitle3"....and so on.
Is this something that is possible? Currently they have no ID when created it is just a normal span.
You can do like following
compareHtml += " </tr><tr>";
for (i = 1; i < compareArr.length-1; i++) {
compareHtml += '<td>' + compareArr[i].journaltitle + '</td>';
journalTitle.append('<span id=journalTitle'+i+'>' + compareArr[i].journaltitle + '</span> ');
}

How to append each object to its respective 'block' of elements?

var clubbingLocations = $('#clubbing-locations');
$.getJSON("/js/location.json", function(data) { //load json
for (var i = 1; i <= data.locations.length; i++){ //loop through json, append html and objects
clubbingLocations.append("<div class='night-type location'>" +
"<a href='location.html'>" +
"<div class='overlay'>" +
"<div class='overlay'>" +
"<span class='fav checked glyphicon glyphicon-heart' aria-hidden='true'></span>" +
"<h4>" + data.locations[i].name + "</h4>" +
"<div class='rating-hold'>" +
"</div>" +
"</div>" +
"</a>" +
"</div>"
);
for (var j = 1; j <= data.locations[i].rating; j++){
$('.rating-hold').append("<span class='filled glyphicon glyphicon-star' aria-hidden='true'></span>");
}
}
I am trying to append the object's review to each of its respective rating-hold, however, the reviews are accumulating and adding themselves on to each other instead of appending to the respective class, them moving on.
The first rating inserts its self perfectly, but after that they start adding themselves onto each other.
Create a jQuery object with your html string first.
Then you can search within that object to find the current rating-hold and append icons to it.
Finally, append the whole object including the icons to clubbingLocations
for (var i = 0; i <= data.locations.length - 1; i++){ //loop through json, append html and objects
// create jQuery object
var $nightType= $("<div class='night-type location'>" +
"<a href='location.html'>" +
"<div class='overlay'>" +
"<div class='overlay'>" +
"<span class='fav checked glyphicon glyphicon-heart' aria-hidden='true'></span>" +
"<h4>" + data.locations[i].name + "</h4>" +
"<div class='rating-hold'>" +
"</div>" +
"</div>" +
"</a>" +
"</div>"
);
for (var j = 0; j <= data.locations[i].rating; j++){
// append icons to object created above
$nightType.find('.rating-hold').append("<span class='filled glyphicon glyphicon-star' aria-hidden='true'></span>");
}
// append object to dom
clubbingLocations.append($nightType);
}
You can use JQuery .each documentation
$('.rating-hold').each(function(index){
$(this).append('html code here');
})
Your are appending using the .rating-hold alone, which will append all to the first location, try giving locations ids, and assign stars to each separately using this instead:
var clubbingLocations = $('#clubbing-locations');
$.getJSON("/js/location.json", function(data) { //load json
for (var i = 0; i <= data.locations.length - 1; i++){ //loop through json, append html and objects
clubbingLocations.append(
"<div id='location" + i + "' class='night-type location'>" +
"<a href='location.html'>" +
"<div class='overlay'>" +
"<div class='overlay'>" +
"<span class='fav checked glyphicon glyphicon-heart' aria-hidden='true'></span>" +
"<h4>" + data.locations[i].name + "</h4>" +
"<div class='rating-hold'>" +
"</div>" +
"</div>" +
"</a>" +
"</div>"
);
for (var j = 0; j <= data.locations[i].rating; j++){
$('#location' + i + ' .rating-hold').append("<span class='filled glyphicon glyphicon-star' aria-hidden='true'></span>");
}
}

this.id is not working to detect which link is clicked in href

I am new to javascript and I am creating a bookstore using the google API. I have a small issue which I couldn't figure out. In the below piece of code that I saw from example code of google api bookstore function, I am trying to create href for the title of the book and pass its selfLink to the destination page i.e book-description.html.
When I put alert(this.id) on onclick It works, but for a normal method get(this) it does not work. I do not need an alertbox I want to take the id of the link clicked in href and pass it to another html.
handleResponse(response) {
for (var i = 0; i < response.items.length; i++) {
var item = response.items[i];
var a = item.volumeInfo.title;
var selfL = item.selfLink;
//var b = a.link("book-description.html");
var image = item.volumeInfo.imageLinks.smallThumbnail;
document.getElementById("content").innerHTML += "</br>" + "</br>" + "<br>" + "<img src =" + "'" + image + "'" + " class='im'/>";
document.getElementById("content").innerHTML += "<h4 class='right'>" + "<a href = 'book-description.html'id = " + "'" + selfL + "'" +
"onclick ='get(this);'>" + a + "</a></h4>";
function get(e) {
var link = e.id;
localStorage.setItem("Link", link);
}
document.getElementById("content").innerHTML += "<h4 class='right'>" + "AUTHOR:" + item.volumeInfo.authors + "</h4>";
document.getElementById("content").innerHTML += "<h5 class='right'>" + "PUBLISHER:" + item.volumeInfo.publisher + "</h5>";
var rating = item.volumeInfo.averageRating;
if (rating) {
document.getElementById("content").innerHTML += "<h5 class='right' id='rating'>" + rating + "</h5>";
} else {
document.getElementById("content").innerHTML += "<h5 class = 'right' id ='rating'>Not Rated Yet</h5>";
}
//document.getElementById("content").innerHTML += "<br>" + "<br>" + "<br>" + item.volumeInfo.publisheddate;
}
}
There are a number of problems with your code, but specifically in answer to your question; your function get is scoped so it is only available within the function handleResponse. For it to be accessible from an onclick it must be in page scope.
Simply move this
function get(e) {
var link = e.id;
localStorage.setItem("Link", link);
}
Into the head of your page
In programming there is the concept of DRY (Don't repeat yourself). So store a reference to document.getElementById("content") and reuse that variable.
var content = document.getElementById("content");
content.innerHTML = ...
You're missing some spaces in your output html. This may work in some browsers, others will struggle
<a href = 'book-description.html'id=
Should have a space between the end of one attribute and the start of another
<a href='book-description.html' id=
And for heaven sake, sort out the concatenation of your strings. You dont need a + if its just a simple string
document.getElementById("content").innerHTML += "</br>" + "</br>";
should be
document.getElementById("content").innerHTML += "</br></br>";

Assign to each user a color

I am currently creating a web-chat and whenever a message is displayed in the chat-box, the user that sent the message is displayed and identified with a color. For every user I create a class and assign a value to the color style with the above function.
newHTML = '';
$.each(data, function(index, element) {
$('.user_' + element.senderId).attr("style","color:" + randColor());
newHTML = newHTML + '<div id="boxMsg"><b><span class="user_' + element.senderId + '">'
+ element.senderId + '</b></span></br>' + element.message + '&nbsp&nbsp<span class="dateMsg">' + dateTime.substring(11, 16) + '</span></div>';
});
$('#chatbox').append(newHTML);
},
A JSON protocol is used to extract all the information concerning the message displayed on the chat. But still it doesn't work and all the usernames are black. Do you know what am I doing wrong?
Thanks in advance for your replies!
EDIT: thanks to #Evan I solved the first part and the function to assign a random color works. But still, only the first and the third member of the chat color changes. The others are still black. Anyway, I leave the code for the function randColor().
function randColor(){
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
};
EDIT.2: I have corrected the function to reflect more the one I am working on.
for (var i = 0; i <= nUsers.length; i++ )
should be
for (var i = 0; i < 6; i++ )
to form a hex color. It should always be 6 (or 3 for short hex colors).
Try to use .attr("style",properties)
If you need to change de background color use the property "background-color":
$('.user_' + element.senderId).attr("style","background-color:" + randColor());
Or, if you need to change de font color use the property "color":
$('.user_' + element.senderId).attr("style","color:" + randColor());
You have error in your HTML-->
var newHTML = '';
newHTML = newHTML + '<div id="boxMsg"><b><span class="user_' + element.senderId + '">' + element.senderId + '</b></span></br>' + element.message + '&nbsp&nbsp<span class="dateMsg">' + dateTime.substring(11, 16) + '</span></div>';
$('#chatbox').append(newHTML);
The "bold" tag closes before the span.
Fix it -->
newHTML = newHTML + '<div id="boxMsg"><b><span class="user_' + element.senderId + '">' + element.senderId + '</span></b></br>' + element.message + '&nbsp&nbsp<span class="dateMsg">' + dateTime.substring(11, 16) + '</span></div>';
Other then that, you can call the randomColor when you build the HTML, instead calling it after with jquery... (and you won't need a special class)-->
newHTML = newHTML + '<div id="boxMsg"><b><span style="color:'+randColor()+'">' + element.senderId + '</span></b></br>' + element.message + '&nbsp&nbsp<span class="dateMsg">' + dateTime.substring(11, 16) + '</span></div>';
I managed to solve the issue and correctly assign a color to each user. This is how the final code looks like:
function randColor(){
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
};
userColor = [];
userColor.push(randColor());
$('.user_' + element.senderId).css("color", userColor);
// Create box messages of the other users
var dateTime = element.timestamp;
newHTML = '<div id="boxMsg"><b><span class="user_' + element.senderId +'" style="color:'+ userColor +'">'+ element.senderId + '</span></b></br>'
+ element.message + '&nbsp&nbsp<span class="dateMsg">' + dateTime.substring(11, 16) + '</span></div>';
$('#chatBox').append(newHTML);
What I did was to create an array, store the obtained colors inside it and finally assign to each class of each user one element inside this array. Thanks to all of you for your answers!

How to make the table in javascript

I have this code to make the data available in table format but the table head and row appear as two different body, how do i work with that
$("#container").html("<table> <th>Name</th> <th>Address</th> <th>Sex</th> <th>Email</th>")
for (var i = 0; i < data.length; i++) {
$("#container").append("<tr><td>" +
data[i].name + "</td><td>" +
data[i].address + "</td><td>" +
data[i].sex + "</td><td>" +
data[i].email + "</td><tr>"
);
}
$("container").append("</table>")
This is what I get
I want the whole table, not two seperate buddies.
var htmlTable = '<table><tr><th>Name</th><th>Adress</th><th>Sex</th> <th>Email</th></tr>';
for(var i = 0; i < data.length; i++) {
htmlTable += '<tr><td>' + data[i].name + '</td><td>' + data[i].adress + '</td><td>' + data[i].sex + '</td><td>' + data[i].email + '</td></tr>';
}
htmlTable += '</table>';
$('#container').html(htmlTable);
Add the table to the DOM at once, otherwise the browser will have problems rendering it.
You can't append <table> and </table> separately, appending DOM elements (by setting innerHTML behind the scene) is not the same as string concatenation. Browser detects invalid markup and fixes it accordingly by adding missing parts of the table. So as the result you get one table after first append, and in the loop you are appending rows into #container, not the table, which is rendered incorrectly.
To fix try something like this:
var $table = $("#container").html("<table><tr><th>Name</th><th>Address</th><th>Sex</th><th>Email</th></tr></table>");
for (var i = 0; i < data.length; i++) {
$table.append("<tr><td>" + data[i].name + "</td><td>" + data[i].address + "</td><td>" + data[i].sex + "</td><td>" + data[i].email + "</td></tr>");
}
Note, I also cached $table variable so you don't query DOM in each iteration.
Also pay attention to closing tags, in your code you have couple of problems like <tr> where it should be </tr>.
You need to add <tr> too for <th>:
$("#container").html("<table> <tr><th>Name</th> <th>Address</th> <th>Sex</th> <th>Email</th></tr></table>")

Categories

Resources