javascript loop thought bootstrap - javascript

I have a simple bootstrap page I need to load JSON data into it:
This is my script:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var tweets = JSON.parse(xhr.responseText);
var tweet = ' <div class="col-xs-12 col-sm-6 col-md-8 col-md-offset-3">';
var name = ' <h4 class="card-title">';
var photo = ' <div class="col-md-4 col-md-offset-3"><div class="col-md-4 ">';
for (var i = 0; i < tweets.length; i += 1) {
name += tweets[i].name;
name += '</h4> </div>';
tweet += ' <div class="jumbotron">';
tweet += ' <p class="card-text">';
tweet += tweets[i].tweet;
tweet += "<br>";
tweet += "</p></div></div>";
photo += ' <img class="img-responsive img-circle" src="user/';
photo += tweets[i].activation;
photo += '/';
photo += tweets[i].pic;
photo += '"></div></div>';
document.getElementById('photo').innerHTML = photo;
document.getElementById('name').innerHTML = name;
document.getElementById('tweet').innerHTML = tweet;
// close all html tags
}
}
};
xhr.open('GET', 'empdata.json');
xhr.send();
And this is my HTML:
<div class="container">
<div class="card">
<div class="card-header">
<div class="row">
<div id="photo">
<!-- here where the pic goes ! -->
</div>
<div id="name">
<!-- here where the name goes ! -->
</div>
</div>
<div class="card-block row">
<div id="tweet">
<!-- here where the tweet goes ! -->
</div>
</div>
</div>
</div>
</div>
</div>
<div class="card-block row">
<div id="tweet"> </div>
</div>
It loops correctly through all JSON data, but it displays all the pictures first then the names and finally the tweets separately. think the problem is related to the mechanism I follow in the loop.

I think you mean to do this. It can be much simpler but without changing your html I would do this:
var container = document.querySelector(".container");
for (var i=0; i<tweets.length; i += 1) {
var name = ' <h4 class="card-title">';
name += tweets[i].name;
name += '</h4> </div>';
var tweet = '<div class="col-xs-12 col-sm-6 col-md-8 col-md-offset-3">'
tweet += ' <div class="jumbotron">';
tweet += ' <p class="card-text">';
tweet += tweets[i].tweet;
tweet += "<br>";
tweet += "</p></div></div>";
var photo ='<div class="col-md-4 col-md-offset-3"><div class="col-md-4 ">'
photo += ' <img class="img-responsive img-circle" src="user/';
photo += tweets[i].activation;
photo += '/';
photo += tweets[i].pic;
photo += '"></div></div>';
container.innerHTML+='<div class="card"><div class="card-header">'+
photo+name+tweet+'</div></div>';
}

EDITED Try set innerText outside from the loop
for (var i=0; i<tweets.length; i += 1) {
name += tweets[i].name;
name += '</h4> </div>';
...
photo += tweets[i].pic;
photo += '"></div></div>';
}
document.getElementById('name').innerHTML = name;
document.getElementById('photo').innerHTML = photo;

Related

Scroll down to specific contact onclick a letter

I created a contact list agenda with a contact-alphapets sidebar filter. What Im trying to achieve is when clicking on a specific letter it will scroll down to the first contact that start with the Letter chosen.
Exemple when I click on Letter A it will scroll down to contacts that starts with the letter A.
Here the code Im using:
HTML part:
<div class="contact-box clearfix">
<div class="contact-cat col-xs-12 col-sm-4 col-lg-3">
<div class="roles-menu">
<ul class="nav">
<li class="contacts_tab active" rel="customers">Customers</li>
<li class="contacts_tab" rel="suppliers">Suppliers</li>
</ul>
</div>
</div>
<div class="contacts-list col-xs-12 col-sm-8 col-lg-9">
<ul class="contact-list" id="contact-list" >
<!-- DISPLAY CONTACTS LIST WITH AJAX-->
</ul>
</div>
<div class="contact-alphapets">
<div class="alphapets-inner">
A
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
Z
</div>
</div>
</div>
Display contacts with ajax/jquery
var baseUrl = $('#baseUrl').val();
$('.contacts_tab').on('click', function(){
var params = $(this).attr('rel');
$('#contact-list > li').remove();
$.ajax({
url: `${baseUrl}api/contacts/list.php?params=${params}`,
success: function (result) {
$.each(result, function(index, data) {
var html = `<li class="${data.firstname.slice(0,1)}">`;
html += '<div class="contact-cont">';
html += '<div class="pull-left user-img m-r-10">';
html += `<img src="${baseUrl}public/attachements/${params}/${data.logo}" alt="" class="w-40 img-circle">`;
html += '</div>';
html += '<div class="contact-info">';
html += `<span class="contact-name text-ellipsis">${data.firstname} ${data.lastname ?? ''}</span>`;
html += `<span class="contact-date"><i class="">${data.phone}</span>`;
html += '</div>';
html += '</div>';
html += '</li>';
$("#contact-list").append(html);
});
}
});
})
The code above works just fine.
Here is the code I tried for the scroll down:
$(".findContact").on('click', function(e){
e.preventDefault();
var findContact = $(this).attr('rel');
$('html,body').animate({ scrollTop: $(`.${findContact}`).offset().top}, 'slow');
})
**

Count DIVs with a dynamic class inside of other DIVs with a dynamic class

I have this horrendous code, it works, but... I am sure you are all gagging at the site of it. What can be done to dynamically place the resortcode into those classes to clean this code up?
What I am trying to achieve is to add the result count in the resortheader for available rooms under each resort. This works, I just know there has to be a better way, but I am not sure how to achieve that.
The code in question is the second set.
Initial code that creates my room DIVs:
let searchresult = function(response) {
let resortCodes = new Set();
for (let j = 0; j < response.length; j++) {
resortCodes.add(response[j].resortcode); // add only happens if the resortcode isn't already in resortCodes
let divID = 'results-' + response[j].resortcode;
let container = document.getElementById(divID);
let price = response[j].points.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
if (response[j].available < 1) {
var available = 'soldoutresult';
var resultClass = response[j].resortcode + 'soldout';
var btn = '<button type="button" class="soldout">SOLD OUT</button>';
}
else {
var available = 'availableresult';
var resultClass = response[j].resortcode + 'roomavail';
var btn = '<button type="button" class="booknow">BOOK NOW</button>';
}
container.innerHTML += `
<div class="${available} roomresults ${resultClass}">
<div class="roomthumb" style="background-image:url(${response[j].roomimgthumb});">
<center><button class="myBtn roomdetailsbtn" data-target="#modal${response[j].roomcode}" data-toggle="modal">Room Details</button></center>
</div>
`
}
};
To Count My DIVs.
let countResults = function(response){
var countAKV = $('div.AKVroomavail').length;
var countAKV2 = $('div.AKV2roomavail').length;
var countAULV = $('div.AULVroomavail').length;
var countBLT = $('div.BLTroomavail').length;
if(countAKV == 0){
document.getElementById('count-akvjh').innerHTML='Sold Out';
}
else {
document.getElementById('count-akvjh').innerHTML = countAKV + " Results";
}
if(countAKV2 == 0){
document.getElementById('count-akvkv').innerHTML='Sold Out';
}
else {
document.getElementById('count-akvkv').innerHTML = countAKV2 + " Results";
}
if(countAULV == 0){
document.getElementById('count-aul').innerHTML='Sold Out';
}
else {
document.getElementById('count-aul').innerHTML = countAULV + " Results";
}
if(countBLT == 0){
document.getElementById('count-blt').innerHTML='Sold Out';
}
}
The HTML:
<div id="akvjhcontainer" class="resortcontainer">
<div id="akvjhheader" class="resortheader">
<div class="headertext"><p class="resortnametext">Animal Kingdom Villas - Jambo House</p><p class="locationtext">Walt Disney World - Orlando, Florida</p></div>
<div class="collapseBTN"><span id="count-akvjh"class="rescount"></span><button class="collstyle" data-toggle="collapse" data-target="#results-AKV"><i></i></button></div>
</div>
<div id="results-AKV" class="results-AKV collapse show"></div>
</div>
<div id="akvkvcontainer" class="resortcontainer">
<div id="akvkvheader" class="resortheader">
<div class="headertext"><p class="resortnametext">Animal Kingdom Villas - Kidani Village</p><p class="locationtext">Walt Disney World - Orlando, Florida</p></div>
<div class="collapseBTN"><span id="count-akvkv"class="rescount"></span><button class="collstyle" data-toggle="collapse" data-target="#results-AKV2"><i></i></button></div>
</div>
<div id="results-AKV2" class="results-AKV2 collapse show"></div>
</div>
<div id="aulcontainer" class="resortcontainer">
<div id="aulheader" class="resortheader">
<div class="headertext"><p class="resortnametext">Aulani</p><p class="locationtext">Kapolei, Hawaii</p></div>
<div class="collapseBTN"><span id="count-aul"class="rescount"></span><button class="collstyle" data-toggle="collapse" data-target="#results-AULV"><i></i></button></div>
</div>
<div id="results-AULV" class="results-AULV collapse show"></div>
</div>
<div id="bltcontainer" class="resortcontainer">
<div id="bltheader" class="resortheader">
<div class="headertext"><p class="resortnametext">Bay Lake Tower</p><p class="locationtext">Walt Disney World - Orlando, Florida</p></div>
<div class="collapseBTN"><span id="count-blt"class="rescount"></span><button class="collstyle" data-toggle="collapse" data-target="#results-BLT"><i></i></button></div>
</div>
<div id="results-BLT" class="results-BLT collapse show"></div>
</div>
Any help is appreciated.
I figured it out. I came across this fiddle: http://jsfiddle.net/dv5gtfcw/
That was submitted as the answer here: counting divs inside div
HTML"
<div id="akvjhcontainer" class="resortcontainer">
<div id="akvjhheader" class="resortheader">
<div class="headertext"><p class="resortnametext">Animal Kingdom Villas - Jambo House</p><p class="locationtext">Walt Disney World - Orlando, Florida</p></div>
<div class="collapseBTN"><span class="countDiv0"></span><button class="collstyle" data-toggle="collapse" data-target="#results-AKV"><i></i></button></div>
</div>
<div id="results-AKV" class="results-AKV collapse show resultcontainer"></div>
</div>
<div id="akvkvcontainer" class="resortcontainer">
<div id="akvkvheader" class="resortheader">
<div class="headertext"><p class="resortnametext">Animal Kingdom Villas - Kidani Village</p><p class="locationtext">Walt Disney World - Orlando, Florida</p></div>
<div class="collapseBTN"><span class="countDiv1"></span><button class="collstyle" data-toggle="collapse" data-target="#results-AKV2"><i></i></button></div>
</div>
<div id="results-AKV2" class="results-AKV2 collapse show resultcontainer"></div>
</div>
$('.resultcontainer').each(function(i) {
var n = $(this).children('.roomavailable').length;
$(".countDiv"+i).text(n + " Results");
console.log(n);
});
let searchresult = function(response) {
let resortCodes = new Set();
for (let j = 0; j < response.length; j++) {
resortCodes.add(response[j].resortcode); // add only happens if the resortcode isn't already in resortCodes
let divID = 'results-' + response[j].resortcode;
let container = document.getElementById(divID);
let price = response[j].points.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
if (response[j].available < 1) {
var available = 'soldoutresult';
var status = 'soldout';
var btn = '<button type="button" class="soldout">SOLD OUT</button>';
}
else {
var available = 'availableresult';
var status = 'available';
var btn = '<button type="button" class="booknow">BOOK NOW</button>';
}
container.innerHTML += `
<div class="${available} roomresults room${status}">

how to set retrived firebase data into div using javascript

I want to put data into div which I already retrieved from firebase. Here is my javascript code:
var rootRef = firebase.database().ref().child("products");
rootRef.on("child_added", snap => {
alert(snap.val());
var image = snap.child("image").val();
var desp = snap.child("description").val();
$("#product_section").append();
});
what should I write into append parenthesis to show data into below format html code:
<div id="product_section" class="container">
<div class="row">
<div class="col-md-6 col-sm-6 productDetails">
<p>Something from description field of Firebase 1 </p>
</div>
<div class="col-md-6 col-sm-6">
<img src="image src form Firebase">
</div>
</div>
<div class="row">
<div class="col-md-6 col-sm-6 productDetails">
<p>Something from description field of Firebase 2 </p>
</div>
<div class="col-md-6 col-sm-6">
<img src="image src form Firebase">
</div>
</div>
</div>
I want to show image and description field between "< img >" and "< p >" respectively.
It seems you almost have the job done.
To put html tags into div, the $("#product_section").append(); need an string as input that holds corresponding structure as followings:
var image_and_desp_string =
'<div class="row">'
+ '<div class="col-md-6 col-sm-6 productDetails">'
+ '<p>' + desp + '</p>'
+ '</div>'
+ '<div class="col-md-6 col-sm-6">'
+ '<img src="' + image + '">'
+ '</div>'
+ '</div>';
$("#product_section").append(image_and_desp_string);
I try to align the code to you html tags so that it is easier to compare.

Change background of dynamic added elements

I want to change the background of the last added element in the dom. To give you a better look here is the html:
<div class="check-in-wrapper">
<div class="ui-grid-a">
<div class="ui-block-a">
<span class="ticket-img">
<img class="image" src="img/icons/ticket.png">
</span>
</div>
<div class="ui-block-b">
<h4>Inchecken</h4>
<div class="check-in-notification-append"></div>
</div>
</div>
</div>
<div class="douane-wrapper">
<div class="ui-grid-a">
<div class="ui-block-a">
<span class="douane-img">
<img class="douane-img image" src="img/icons/douane.png">
</span>
</div>
<div class="ui-block-b">
<h4>Douane</h4>
<div class="douane-notification-append"></div>
</div>
</div>
</div>
<div class="gate-wrapper">
<div class="ui-grid-a">
<div class="ui-block-a">
<span class="gate-img">
<img class="gate-img image" src="img/icons/gate.png">
</span>
</div>
<div class="ui-block-b">
<h4>Gate</h4>
<div class="gate-notification-append"></div>
</div>
</div>
Where I append the elements to check-in-notification-append, douane-in-notification-append, gate-in-notification-append here a better look at the js file.
$(document).on("pagebeforeshow","#progress",function(){
var incheckHtml = '';
var douaneHtml = '';
var gateHtml = '';
for(var count = 0; count < info.data.length; count++){
var shortmessage = info.data[count][3];
var category = info.data[count][4];
var typeOf = info.data[count][5];
if(typeOf === "warning"){
imgPath = 'img/icons/alarm.png';
} else {
imgPath = 'img/icons/alert.png';
}
if (!Array.prototype.last){
Array.prototype.last = function(){
return this[this.length - 1];
};
};
if (category === 'inchecken'){
incheckHtml = incheckHtml + "<div class='notification-item'><img class='notification-image' src=" + imgPath + "><span class='notification-text'>" + shortmessage + "</span></div>";
// $('.check-in-wrapper').empty().prepend(incheckHtml);
$('.check-in-notification-append').empty().prepend(incheckHtml);
}
if(category === 'douane'){
douaneHtml = douaneHtml + "<div class='notification-item overlay'><img class='notification-image' src=" + imgPath + "><span class='notification-text'>" + shortmessage + "</span></div>";
$('.douane-notification-append').empty().prepend(douaneHtml);
}
if(category === 'gate'){
gateHtml = gateHtml + "<div class='notification-item overlay'><img class='notification-image' src=" + imgPath + "><span class='notification-text'>" + shortmessage + "</span></div>";
$('.gate-notification-append').empty().prepend(gateHtml);
}
}
});
But how do I acces the last added element in any category which removes the class "overlay". I'll hope someone could help me out accessing the last added element and removeClass overlay. I have written an .last() function but this will only give me the output of the last object in array...
I think you could achieve this by having some common selector which applies to all the elements that could be affected and using Jquery's last() function.
$(".allMyThings").last().removeClass("overlay");
https://api.jquery.com/last/

Sorting script inside function doesn't work correctly

I'm trying to turn a script into a function, because it's very tiresome repeating the same code over and over again.
The script selects a container which will be holding a new accordion soon. Every accordion inside the container has a unique data-sort id. (It needs to sort from 1 to 10)
It then detects if there are any accordions with an id smaller or bigger than it and adds itself between them.
The script works correctly without it being inside a function.
This script without a function works correctly
var $container = $('.panel-group[data-group-holder="' + dataPlace + '"]'),
$d = $container.find('div.panel-default'),
$n = $('<div class="panel panel-default dragged-true" data-sort="' + dataSort + '"><div class="panel-heading"><h4 class="panel-title"><a class="accordion-toggle sub" data-sort="' + dataSort + '" data-toggle="collapse" href="#main-' + dataSort + '"><div class="remove set"><i class="icon-remove"></i></div>' + dataHtml + ' <b>(<span class="sub-count">0</span>)</b><i class="icon-angle-down"></i></a></h4></div><div id="main-' + dataSort + '" class="panel-collapse in"><div class="panel-body" data-accept="' + dataSort + '"></div></div></div>');
var $a = $d.filter(function () {
return $(this).data('sort') < dataSort;
}).last();
$(that).parents('div:eq(0)').remove();
/*alert($('.draggable-groups .main-groups[data-sort="' + dataSort + '"]').parents().html());*/
if ($a.length) $a.after($n);
else $container.prepend($n);
This function does not work correctly (it doesn't sort)
function placeSort(thisContainer, containerFind, placeHtml, returnCompareOneFind, returnCompareOne, returnCompareTwo, removeClone) {
var $container = $(thisContainer),
$d = $container.find(containerFind),
$n = $(placeHtml);
if(returnCompareOneFind == "false") {
var $a = $d.filter(function () {
return $(this).data(returnCompareOne) < returnCompareTwo;
}).last();
} else {
var $a = $d.filter(function () {
return $(this).find(returnCompareOneFind).data(returnCompareOne) < returnCompareTwo;
}).last();
}
removeClone;
if ($a.length) $a.after($n);
else $container.prepend($n);
}
function addGroupAccordion(that, dataSort, dataPlace, dataHtml) {
var thisContainer = '.panel-group[data-group-holder="' + dataPlace + '"]';
var containerFind = 'div.panel-default';
var placeHtml = '<div class="panel panel-default dragged-true" data-sort="' + dataSort + '"><div class="panel-heading"><h4 class="panel-title"><a class="accordion-toggle sub" data-sort="' + dataSort + '" data-toggle="collapse" href="#main-' + dataSort + '"><div class="remove set"><i class="icon-remove"></i></div>' + dataHtml + ' <b>(<span class="sub-count">0</span>)</b><i class="icon-angle-down"></i></a></h4></div><div id="main-' + dataSort + '" class="panel-collapse in"><div class="panel-body" data-accept="' + dataSort + '"></div></div></div>';
var returnCompareOneFind = "false";
var returnCompareOne = 'sort';
var returnCompareTwo = dataSort;
var removeClone = $(that).parents('div:eq(0)').remove();
placeSort(thisContainer, containerFind, placeHtml, returnCompareOne, returnCompareTwo, removeClone);
}
$(document).on('click','.draggable-groups .main-groups',function(){
var dataSort = $(this).attr("data-sort");
var dataPlace = $(this).parents('div:eq(1)').attr("data-group");
var dataHtml = $(this).html();
var that = $(this);
addGroupAccordion(that, dataSort, dataPlace, dataHtml);
var groupHolder = dataPlace;
countChildren(groupHolder);
});
HTML
<div class="panel panel-default">
<div class="panel-heading main">
<h4 class="panel-title">
<a class="accordion-toggle collapsed main side-js" data-parent="#main-panel" data-panel="00" data-toggle="collapse" href="#panel-00">
<span>0</span>Tellija kulud
<b>(<span class="cat-count">0</span>)</b>
<i class="icon-angle-down"></i>
</a>
</h4>
</div>
<div id="panel-00" class="panel-collapse collapse">
<div class="panel-body">
<div class="panel-group" data-group-holder="00">
</div>
</div>
</div>
</div>
<h3>Main groups</h3>
<div class="row draggable-groups" data-group="00">
<div class="col-md-6">
<div class="main-groups" data-sort="01">01</div>
</div>
<div class="col-md-6">
<div class="main-groups" data-sort="02">02</div>
</div>
<div class="col-md-6">
<div class="main-groups" data-sort="03">03</div>
</div>
<div class="col-md-6">
<div class="main-groups" data-sort="04">04</div>
</div>
<div class="col-md-6">
<div class="main-groups" data-sort="05">05</div>
</div>
<div class="col-md-6">
<div class="main-groups" data-sort="06">06</div>
</div>
<div class="col-md-6">
<div class="main-groups" data-sort="07">07</div>
</div>
<div class="col-md-6">
<div class="main-groups" data-sort="08">08</div>
</div>
</div>
Creating a jsFiddle would take too much time recreating this. I'm sorry for lacking it.
Your issue likely comes down to an issue with trying to pass this
Give this a try:
function addGroupAccordion(self, dataSort, dataPlace, dataHtml) {
...
var removeClone = $(self).parents('div:eq(0)').remove();
...
}
$(document).on('click','.draggable-groups .main-groups',function(){
...
var self = this; // 'self' is more standardized
addGroupAccordion(self, dataSort, dataPlace, dataHtml);
...
});
What is going on here is that when you were setting var that = $(this); in the $().on function, you were storing the jQuery object containing this, then when you were trying to use it in the addGroupAccordion function by using $(that), you were asking jQuery to do: $($(this)).

Categories

Resources