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

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>");
}
}

Related

Jquery: append to div with a class that has a variable name

So I'm working on a quick app that when you press a button, dog pictures show up. I want the pictures to appear in rows. So I started to create divs with the class 'dog row' and ended the name with a variable.
While the creation of that div is successful. I can't seem to append anything to the div itself.
for (i=0; i<dogPool.length; i++){
if (i%5 == 0){
$('.dogTable').append(
"<div class='dogLine dogRow" + rowNumber + "'></div>"
);
console.log("<div class='dogLine dogRow" + rowNumber + "'></div>");
rowName = "'.dogRow" + rowNumber + "'";
rowNumber++;
}
console.log("row: " + rowName);
$(rowName).append(
"<p>"+ i + "</p>"
);
}
The problem is here rowName = "'.dogRow" + rowNumber + "'";
You should fix like this
var rowName = '.dogRow' + rowNumber;
var dogPool = ["dog1", "dog2"];
var rowNumber = 0;
for (i=0; i<dogPool.length; i++){
$('.dogTable').append(
"<div class='dogLine dogRow" + rowNumber + "'></div>"
);
console.log("<div class='dogLine dogRow" + rowNumber + "'></div>");
var rowName = '.dogRow' + rowNumber;
rowNumber++;
$(rowName).append(
"<p>"+ i + "</p>"
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="dogTable">
123
</div>

Inserting custom text in JS output

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>';

Removing objects from an array onclick

I have a an array of items which holds item objects. I want to create a function that when I click on a certain item it is removed from the array. I know I need to use something like splice and I have implemented the following solution but it does the seem to work.
Can anyone tell me what am I doing wrong.
function updateView() {
for (var i = 0; i < storeItems.length; i++) {
output += "<a href='#' id='itemTitle' onclick='removeRecord(" + i + ");'>"
+ storeItems[i].title + " " + "\n" + "</a>";
}
function removeRecord(i) {
storeItems.splice(i, 1);
var newItem = "";
// re-display the records from storeItems.
for (var i = 0; i < storeItems.length; i++) {
newItem += "<a href='#' onclick='removeRecord(" + i + ");'>X</a> "
+ storeItems[i] + " <br>";
};
document.getElementById('foods').innerHTML = newItem;
}
I think this the error is in the line below:
output += "<a href='#' id='itemTitle' onclick='removeRecord(" + i + ");'>" + storeItems[i].title + " " + "\n" + "</a>";
Because it does not recognise the "onclick" event even when I try to do a test with a simple alert.
Can anyone tell me what am I doing wrong. Also if you think you need more information to answer this question please let me know.
Thank you in advance.
Try ...
storeItems = storeItems.splice(i, 1);
WRONG: Basically, you have to assign the spliced array to something.
UODATE:
Here's the way I would do it ... tested in jsFiddle:
var storeItems = [{
title: "Dog"
}, {
title: "Cat"
}, {
title: "Bird"
}];
var foods = document.getElementById('foods');
foods.addEventListener('click', function(e) {
var index = e.target.getAttribute('value');
storeItems.splice(index, 1);
// re-display the records from storeItems.
updateView();
});
function updateView() {
var output = "";
for (var i = 0; i < storeItems.length; i++) {
output += "<a href='#' class='item' value='" + i + "'>" + storeItems[i].title + " " + "\n" + "</a>";
}
document.getElementById('foods').innerHTML = output;
}
updateView();
HTML:
<div id='foods'></div>
This effectively takes the onclick event off of the anchor tag (you could have them on any type of tag at this point) and I also reused your updateView code in the Listener so that it only needs maintained in one location.

How to add new class to the existing class in this case

I am new to Javascript and Jquery so please excuse if this is a dumb question
HTML is being constructed dynamically as shown
var favoriteresultag = '<ul>';
favoriteresultag += "<section id='"+name+"' class='ulseWrap lielement'>" + "<div class='intit someclassss'>"+ name + "</div>" + "</section>";
How can i add/concat one more variable to the class ulseWrap lielement ??
I tried this way
var classactive = '';
if (some condition) {
classactive = 'activeRest';
} else {
classactive = '';
}
favoriteresultag += "<section id='" + name + "' class='ulseWrap lielement '+classactive+' '>" + "<div class='intit someclassss'>" + name + "</div>" + "</section>";
String concatenation, just like you're doing:
favoriteresultag += "<section id='"+name+"' class='ulseWrap lielement " + classactive + "'>" + "<div class='intit someclassss'>"+ name + "</div>" + "</section>";
Try this with jquery if you are using it
$('.actual_class').addClass('new_class')
In your case can be
$('#'+name).addClass('activeRest')
or
$('.ulseWrap.lielement').addClass('activeRest')

jquery won't update dynamically generated html

I have an ajax function that loads my inbox messages and each of the messages has a user_type and read field.
I'm looping over the messages and generating the html for them.
function initializeMailbox() {
// get all mailbox data
user.GetInboxMessages(function (response) {
if (response) {
inboxMessages['inbox'] = response;
$("#inbox-table").fadeIn();
loadInboxTable();
inboxDataTable = $("#inboxTable").dataTable();
$("#inbox-count").html(inbox_msg_count);
displayMessage(first_msg_id);
}
});
}
function loadInboxTable() {
for (var i = 0; i < inboxMessages['inbox'].length - 1; i++) {
first_msg_id = inboxMessages['inbox'][0].message_id;
var user_type = "";
if (inboxMessages['inbox'][i].user_type = 1)
user_type = "DONOR";
else if (inboxMessages['inbox'][i].user_type = 0)
user_type = "CANDIDATE";
else if (inboxMessages['inbox'][i].user_type = 2)
user_type = "GROUP";
$("#inbox-table-body").append(
"<tr class='data-row' style='height: 75px;'> " +
"<td>" +
"<input type='hidden' id='user_type' value='" + inboxMessages['inbox'][i].user_type + "'/>" +
"<input type='hidden' id='read' value='" + inboxMessages['inbox'][i].read + "'/>" +
"<input type='checkbox' id='" + inboxMessages['inbox'][i].message_id + "'></input></td>" +
"<td>" +
"<p class='left'>" +
"<img class='td-avatar' style='margin-top: 0px !important;' src='/uploads/profile-pictures/" + inboxMessages['inbox'][i].image + "' alt='avatar'/>" +
"<br/>" +
"<span class='user-type'>" + user_type + "</span>" +
"</p></td><td>" +
"<h2 onclick='displayMessage(" + inboxMessages['inbox'][i].message_id + ");'>" + inboxMessages['inbox'][i].firstname + " " + inboxMessages['inbox'][i].lastname + "</h2><br/>" +
"<h3 class='message-subject' onclick='displayMessage(" + inboxMessages['inbox'][i].message_id + ");'>" + inboxMessages['inbox'][i].subject + "</h3><br/><br/>" +
"<h3 style='font-size: 0.7em; margin-top: -25px; float:left;'><span>" + inboxMessages['inbox'][i].datesent.toString().split(" ")[0] + "</span></h3>" +
"</td>" +
"<td><button class='delete-item' onclick='deleteMessage(" + inboxMessages['inbox'][i].message_id + ");' src='/images/delete-item.gif' alt='Delete Message' title='Delete Message' style='cursor: pointer; float:left; margin-left: 5px; margin-top:-3px;'></button></td>" +
"</tr>"
);
// check if the message has been read
if (inboxMessages['inbox'][i].read == 0) {
// not read
$("#message-subject").addClass('read-message');
} else {
// read
$("#message-subject").removeClass('read-message');
}
inbox_msg_count++;
}
}
Now if I alert out the values of user_type and read, I get the correct values, based on the message it's iterating over. But when it outputs, it's only using the value of the first message.
I need to be able to dynamically style the messages with jquery, based on these values. Can someone please tell me why this isn't working...
Well, for one thing, you are using an ID selector:
$("#message-subject").addClass('read-message');
When you actually have a class:
<h3 class='message-subject'...
Use:
$(".message-subject").addClass('read-message');
Secondly, you are making an assignment (=) instead of doing a comparison (==) on user_type.
Might I suggest a different approach instead of a big if..then..else?
Use an array to index your user_types:
var user_type_labels = [ 'CANDIDATE', 'DONOR', 'GROUP' ];
function loadInboxTable() {
for (var i = 0; i < inboxMessages['inbox'].length - 1; i++) {
first_msg_id = inboxMessages['inbox'][0].message_id;
// One line instead of an if/then/else
var user_type = user_type_labels[ inboxMessages['inbox'][i].user_type ];
...
Third, you are adding multiple items with the same ID to your DOM. This is not legal and has undefined consequences.
<input type='hidden' id='user_type' value='...
<input type='hidden' id='read' value='...
You need to use classes for this.
<input type='hidden' class='user_type' value='...
<input type='hidden' class='read' value='...
In your code I think you meant to do the following
if (inboxMessages['inbox'][i].user_type === 1)
Notice the equal signs. What you currently have will always be true and user_type will always be assigned to DONOR

Categories

Resources