Display user data inside div - blocks - javascript

I am trying to display user data in div blocks depending upon the number of users. I will get the number of users and data from server using ajax. I want to display the user data in a separate div block. If the number of users is 2, I want to display two blocks , 3 users in three blocks...I defined a div
<div class = "users> </div>.
Inside this div, I want to append the users details like
<div class=" user1"> <p><span class="name"></span></p>
<p><span class="age"></span></p>
<p><span class="address"></span></p>
</div>
using jQuery. If there are two users, I have to display the blocks in the center. Depending upon the number of users , I have to align the blocks.(For ex : 6 users - 3 in one row)
How to display the data inside the div?
code:
<div class="users">
<div class="user1">
<p> <span class="name"> </span> </p>
<p> <span class="age"> </span> </p>
<p> <span class="address"> </span> </p>
<p> <span class="phone"> </span> </p>
</div>
<div class="user2">
<p> <span class="name"> </span> </p>
<p> <span class="age"> </span> </p>
<p> <span class="address"> </span> </p>
<p> <span class="phone"> </span> </p>
</div>
</div>
for(var user_name in res) {
$.ajax({
type: 'GET',
timeout: 10000,
dataType: 'json',
url: multidashboard_info_url + '?client=' + user_name,
async: true,
})
.done(function(data) {
console.log(" success and data is ",data);
var dashboard_info = data["dashboard_info"];
var name = dashboard_info["details"]["name"],
age = dashboard_info["details"]["age"],
address = dashboard_info["details"]["address"],
})
.fail(function() {
console.log("error");
})
}

You can use append() method to add content inside html and for multiple solution, you need to create a dynamic function like this:
Here is working jsFiddle.
function addUserData($selector,name,age,address) {
$selector.append('<p><span class="name">'+ name +'</span></p>' +
'<p><span class="age">'+ age +'</span></p>' +
'<p><span class="address">'+ address +'</span></p>');
}
var name1 = 'John',
age1 = 23,
address1 = 'New York';
addUserData($('.user1'),name1,age1,address1);
var name2 = 'Wall',
age2 = 32,
address2 = 'Istanbul';
addUserData($('.user2'),name2,age2,address2);

You may wanna try something like this:
//this object you should be returned as a json_encoded(USERS_ARRAY) at your php controller
var jsonEncodedObject = '[{"name":"Gonsalo Sousa","age":23,"address":"Some Address"},{"name":"Jonh Doe","age":40,"address":"Some Address"}]';
//parseJSON to use with jscript
var users = $.parseJSON(jsonEncodedObject);
//now run the object using $.each()
$(users).each(function(index) {
//appends each user to the #users <div>
$('#users').append('<div class="user' + index + '"><p><span class="name">' + this.name + '</span></p>' + '<p><span class="age">' + this.age + '</span></p>' + '<p><span class="address">' + this.address + '</span></p></div>');
});
[class*="user"] {
border: 1px solid black;
margin-bottom: 5px;
padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="users"></div>
UPDATE
Maybe this can help you
var i = 0;
jQuery(dashboard_info["details"]).each(function(){
var className = "user"+i;
jQuery('#users').append('<div class="'+className+'">/*rest of your html*/</div>')
i++;
});

Related

JQUERY/AJAX-multiply classes based on content number

I'm trying to extract specific data and send them to the client side so in order to achieve that I used AJAX like below :
<script type ="text/Javascript">
$(document).ready(() => {
$.ajax({
type: 'GET',
dataType : 'json',
url: '/envoi/events/',
})
.done(function(data) {
for(let i =0; i< data.length;i++) {
console.log(data[i].events.eventName);
$("#event1").html(`<b>${data[i].events.eventName}</b>`) // event1 is the id of field name
$("#time1").html(`<b>${data[i].events.eventDate} - ${data[i].events.targetReminder} |
${data[i].events.targetAmPM} </b>`)// time1is the id of field time and date
$("#comment1").html(`<b>${data[i].events.caption}</b>`) // comment1 is the id of field description
$("#location1").html(`<b>${data[i].events.location}</b>`) // location1 is the id of field location
}
})
.fail(function(xhr, status, error) {
console.log(error);
})
.always(function(data){
});
})
</script>
and this is the output
this script works perfectly and fill one container with the requested values but what I'm looking for is to fill every container and multiply them based on data found from my db
which mean :
1- if there is more than one data data[i].events.eventName or other another container must be created and get filled by the new value
the HTML code is below :
<div class="card">
<div class="card-header" id="headingOne-1">
<script type ="text/Javascript">
$(document).ready(() => {
$.ajax({
type: 'GET',
dataType : 'json',
url: '/envoi/events/',
})
.done(function(data) {
for(let i =0; i< data.length;i++) {
console.log(data[i].events.eventName);
$("#event1").html(`<b>${data[i].events.eventName}</b>`)
$("#time1").html(`<b>${data[i].events.eventDate} - ${data[i].events.targetReminder} | ${data[i].events.targetAmPM} </b>`)
$("#comment1").html(`<b>${data[i].events.caption}</b>`)
$("#location1").html(`<b>${data[i].events.location}</b>`)
}
})
.fail(function(xhr, status, error) {
console.log(error);
})
.always(function(data){
});
})
</script>
<div class="event-time">
<time id="time1" datetime="2004-07-24T18:18">9:00am</time>
<div class="more"><svg class="olymp-three-dots-icon"><use xlink:href="svg-icons/sprites/icons.svg#olymp-three-dots-icon"></use></svg>
<ul class="more-dropdown">
<li>
Mark as Completed
</li>
<li>
Delete Event
</li>
</ul>
</div>
</div>
<h5 class="mb-0 title">
<a href="#" data-toggle="collapse" data-target="#collapseOne-1" aria-expanded="true" aria-controls="collapseOne" id = "event1">
Breakfast at the Agency
<i class="fa fa-angle-down" aria-hidden="true"></i>
<span class="event-status-icon" data-toggle="modal" data-target="#public-event">
<svg class="olymp-calendar-icon" data-toggle="tooltip" data-placement="top" data-original-title="UNCOMPLETED"><use xlink:href="svg-icons/sprites/icons.svg#olymp-calendar-icon"></use></svg>
</span>
</a>
</h5>
</div>
<div id="#collapseOne-1" class="collapse show" aria-labelledby="headingOne" data-parent="#headingOne-1">
<div class="card-body" id ="comment1">
Hi Guys! I propose to go a litle earlier at the agency to have breakfast and talk a little more about the new design project we have been working on. Cheers!
</div>
<div class="place inline-items">
<svg class="olymp-add-a-place-icon"><use xlink:href="svg-icons/sprites/icons.svg#olymp-add-a-place-icon"></use></svg>
<span id ="location1">Daydreamz Agency</span>
</div>
</div>
</div>
Any idea how to multiply that box based on data found with the script mentioned above ?
Hope I mentioned everything :-D ?
Best Regards,
Every time your loop works, $("#event1").html(....), $("#-----").html(....) will be replaced with your new values. So why don't you rather create a variable name html outside a loop and every div section or html tags that needs to be rendered in DOM, inside the loop and append after the div you want to render. Like mentioned on above answer,
var html="";
for(let i =0; i< data.length;i++){
html += `<div class="card-header"> ${data[i].event.eventName} </div>` +
`<div class=" -----"> $${data[i].event.eventDate} ` +
------------------and so on---------------------------;
}
$("#NAME OF ID BEHIND YOU WANT TO SHOW YOUR NEW DIV").append(html);
Hope it will work :)
I believe you should just create the whole HTML in javascript then append that HTML to DOM. for example.
let html = "";
for(let i =0; i< data.length;i++) {
html += "<p>"+ data[i].events.eventName + "</p>";
html += "<p>"+ data[i].events.eventDate + "</p>";
}
$("#ParentDivIDWhereToAppendThisContent").html(html);
The above code is just an example of how you can do it. You need to customize it to suit your needs.

Load More Button JS - Load new content on page

I'm trying to develop a Load-More button using Javascript calling an API done with PHP.
So far, so good. I can load the new objects in a range i += i + 4 (I load three new comments everytime I press the button).
This is my load-more button:
$(document).ready(function () {
$(".load-more").on('click', function () {
var tab = $(this).data('tab');
var next_page = $(this).data('next-page');
console.log(next_page);
console.log(tab);
$.get($(this).data('url') + '?tab=' + tab + '&page=' + next_page, function (data) {
addNewQuestions($.parseJSON(data));
});
});
});
And for every object loaded I want to print each of these html blocks.
<div class="question-summary narrow">
<div class="col-md-12">
<div class="votes">
<div class="mini-counts"><span title="7 votes">
{if $question['votes_count']}
{$question['votes_count']}
{else}
0
{/if}
</span></div>
<div>votes</div>
</div>
<div {if $question['solved_date']}
class="status answered-accepted"
{else}
class="status answer-selected"
{/if}
title="one of the answers was accepted as the correct answer">
<div class="mini-counts"><span title="1 answer">{$question['answers_count']}</span></div>
<div>answer</div>
</div>
<div class="views">
<div class="mini-counts"><span title="140 views">{$question['views_counter']}</span></div>
<div>views</div>
</div>
<div class="summary">
<h3>
<a href="{questionUrl($question['publicationid'])}" class="question-title" style="font-size: 15px; line-height: 1.4; margin-bottom: .5em;">
{$question['title']}
</a>
</h3>
</div>
<div class = "statistics col-sm-12 text-right" style="padding-top: 8px">
<span>
<i class = "glyphicon glyphicon-time"></i>
<span class="question-updated-at">{$question['creation_date']}</span>
</span>
<span>
<i class = "glyphicon glyphicon-comment"></i>
<span class="question-answers">{$question['answers_count']}</span>
</span>
</div>
</div>
</div>
The problem is that I have several conditions, as {if$question['votes_count']} and I'm struggling because I don't know how get those variables when rendering the html.
Then I found something but I can't figure out how to adapt to my case
On that addNewQuestions I think that a good approach would be:
function addNewQuestions(objects) {
$.each(objects, function (i, object) {
console.log(object);
var lastItem = $('div.active[role="tabpanel"] .question-line:last');
var newLine = lastItem.clone(true);
var newObject = newLine.find('.question-col:eq(' + i + ')');
newObject.find('.question-info-container').attr('data-id', object.publicationid);
newObject.find('.vote-count').html(object.votes);
updateTitleAndLink(newObject.find('.question-title'), object);
lastItem.after(newLine);
});
}
function updateTitleAndLink(questionTitle, object) {
questionTitle.attr('href', questionTitle.data('base-question-url') + object.publicationid);
questionTitle.html(object.title);
}
But nothing happens and I can't figure out why.
Any idea or suggestion?
Kind regards

jquery each() and js array not working as expected

I have this code in html:
<div class="box-content">
<span>
<h4 id="title">title1</h4>
<h5 id="texto"></h5>
</span>
<span>
<h4 id="title">title2</h4>
<h5 id="texto"></h5>
</span>
<span>
<h4 id="title">title3</h4>
<h5 id="texto"></h5>
</span>
....
</div>
and I need to populate that structure using an array as follows
$(".pluscontrol").click(function(){
var itemBoxValues1 = ["text1", "text2", "text3"];
var i = 0;
$('.box-content').children().each(function(){
var tmp = itemBoxValues1[i];
$('.box-content').children().children("h5").text(" id: "+i+" val "+tmp);
i++;
});
});
but it doesn't work as I expected because in all <h5> elements print this:
<span>
<h4 id="title">title n </h4>
<h5 id="texto">id: 35 val 23</h5>
</span>
I don't understand why it's happen. Thanks.
Make your selector tighter so you don't need .children() methods. With .each() you don't need to increment i because it's built in and the this is also established as well.
Also, you need to use class instead of id, because id must be unique per document (i.e. the webpage). With classes (which you'll need to change to or HTML is not valid), you could use $('.texto') instead of $(.box-content h5').
$(".pluscontrol").click(function() {
var tmp = ["text1", "text2", "text3"];
$('.box-content h5').each(function(i) {
$(this).text(" id: " + i + " val: " + tmp[i]);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box-content">
<span>
<h4 class="title">title1</h4>
<h5 class="texto"></h5>
</span>
<span>
<h4 class="title">title2</h4>
<h5 class="texto"></h5>
</span>
<span>
<h4 class="title">title3</h4>
<h5 class="texto"></h5>
</span>
<button class='pluscontrol'>GO</button>
Try this:
$(".pluscontrol").click(function(){
var itemBoxValues1 = ["text1", "text2", "text3"];
var i = 0;
$('.box-content').children().each(function(){
var tmp = itemBoxValues1[i];
$(this).children("h5").text(" id: "+ i +" val "+ tmp);
i++;
});
});
Update
Inside each, you need to find children of current span, so you need to use $(this), this $('.box-content').children().children("h5") will return all h5 tags
Also you can use following to save some lines of your code:
var itemBoxValues1 = ["text1", "text2", "text3"];
$('.box-content > span').each(function(i, span){
$(span).children("h5").text(" id: "+ i +" val "+ itemBoxValues1[i]);
});
try this :
<html>
<head></head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<style type="text/css">
[class^="B_class"]:first-child{
display: none;
}
</style>
<body>
<div class="box-content">
<span>
<h4 id="title">title1</h4>
<h5 id="text0"></h5>
</span>
<span>
<h4 id="title">title2</h4>
<h5 id="text1"></h5>
</span>
<span>
<h4 id="title">title3</h4>
<h5 id="text2"></h5>
</span>
<input type="button" value="plus+" id="plus">
</div>
</body>
<script type="text/javascript">
$(document).ready(function(){
var items = $(".box-content span").length;
var itemBoxValues1 = ["text1", "text2", "text3"];
$("#plus").click(function(){
for(var i=0;i<items;i++)
{
var tmp = itemBoxValues1[i];
var theid = "#text"+i;
$(theid).text("id :"+i+" val "+tmp);
}
});
});
</script>
</html>
note : don't use same id name for elements.
You are getting id: 35 val 23 in each iteration because the reference to each of the span elements is getting overwritten every time the loop runs (more explanation below).
I would write it like this:
$(".pluscontrol").click(function(){
var itemBoxValues1 = ["text1", "text2", "text3"];
$('.box-content').children().each(function(i){
var tmp = itemBoxValues1[i];
$(this).children("h5").text(" id: " + i + " val: " + tmp);
});
});
You don't need variable "i", nor do you need to increment it inside the loop. jQuery.each() gives you an index variable and automatically increments it inside the loop.
You don't need to re-query the DOM for the children of your span elements. Just call $(this) to get the spans, 'this' is a reference to each object being iterated inside the loop.
An id by definition is unique. You can use data- attributes or a class instead.
Here's how you may re-write your code to take advantage of all the available data:
$('.box-content > span').each(function(i,v) {
$(v).find('h5').text(' id: ' + (i+1) + '; val: ' + $(v).find('h4').text() );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box-content">
<span>
<h4 data-id="title">title1</h4>
<h5 data-id="texto"></h5>
</span>
<span>
<h4 data-id="title">title2</h4>
<h5 data-id="texto"></h5>
</span>
<span>
<h4 data-id="title">title3</h4>
<h5 data-id="texto"></h5>
</span>
....
</div>

i want to associate links to respective article on dynamically created p element

here is my codepen link
my html code
<div id="main">
<h1>Wikipedia Viewer</h1>
<form class="form-inline">
<div class="container">
<div class="row">
<div class="col-sm-6 col-sm-offset-4 col-lg-7 col-lg-offset-4">
<div class="form-group">
<label class="sr-only" for="search">search</label>
<input type="text" class="form-control" placeholder="Search">
</div>
<button type="button" class="btn btn-primary"><i class="fa fa-search"></i></button></form>
</div>
</div>
</div>
Surprise me!
</div>
<div id="search">
</search>
jquery code for making wikipedia api search call and then displaying title and overview.i want to associate links to respective article on dynamically created p element
$(document).ready(function() {
$("button").click(function() {
var article = $("input").val();
$.ajax({ //wikipedia api call
url: "https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=" + article + "&format=json",
dataType: "jsonp",
success: function(data) {
for (var i = 0; i < data.query.search.length; i++) { //displaying titles and snippets accroding to search query. i want to associate link to each dynamically created p element.
var title = data.query.search[i].title;
var snippet = data.query.search[i].snippet;
$("#search").append("<p>" + title + "<br>" + snippet + "</p>");
}
$("#main").attr({
'style': 'display: none'
});
},
error: function() {
$("h1").html("oops");
}
});
});
});
Change your $("#search").append() as follows:
$("#search")
.append("<p><a href='https://en.wikipedia.org/wiki/" + title + "'>" + title + "</a>" +
"<br>" + snippet + "</p>"
);
Codepen

Javascript .click() not working

I'm creating a store locator for a website and ive got a tooltip box that displays an email the i want to make a link. this is the html:
<div class="gm_popup">
<span class="address"> Address</span><br>
<span class="city"> City</span><br>
<span class="phone"> 123 456</span><br>
<span class="email"> email#example.com</span><br>
</div>
and this is the js:
jQuery(document).ready(function(){
var old_focus_and_popup = focus_and_popup;
focus_and_popup = function (id){
return_val = old_focus_and_popup (id);
setTimeout(function (){
jQuery("#store_map .gm_popup .email").click(function(){
var text = jQuery(this).text();
document.location = "mailto:" + text.trim();
});
jQuery(".gm_popup .email").css('text-decoration','underline').css('color','#2aa8e0');
}, 200);
return return_val ;
}
});
any idea why this wouldnt be working? after adding some console.logs it seems like its getting as far as the .click but no going inside the function. Thanks
You are registering click event
This won't trigger until any click is done manually.
If you wanna get auto click then try like this after registering click event
jQuery("#store_map .gm_popup .email").click();
or
jQuery("#store_map .gm_popup .email").trigger("click");
Well you have all the events code inside the function, and you never end up calling that function. So I've made some changes, removed the setTimeout, as that was unnecessary. Also, made a call to that function.
<div id="store_map">
<div class="gm_popup">
<span class="address"> Address</span><br>
<span class="city"> City</span><br>
<span class="phone"> 123 456</span><br>
<span class="email"> email#example.com</span><br>
</div>
</div>
jQuery(document).ready(function(){
focus_and_popup = function (id){
//return_val = old_focus_and_popup (id);
jQuery("#store_map .gm_popup .email").click(function(){
var text = jQuery(this).text();
console.log("HERE");
document.location = "mailto:" + text.trim();
});
jQuery(".gm_popup .email").css('text-decoration','underline').css('color','#2aa8e0');
return return_val ;
}
focus_and_popup();
var old_focus_and_popup = focus_and_popup;
});
I wrote for you a snippet that simply works.
jQuery(document).ready(function () {
jQuery(".gm_popup .email").click(function () {
alert('hello');
var text = jQuery(this).text();
document.location = "mailto:" + text.trim();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="gm_popup">
<span class="address"> Address</span>
<br>
<span class="city"> City</span>
<br>
<span class="phone"> 123 456</span>
<br>
<span class="email"> email#example.com</span>
<br>
</div>

Categories

Resources