I have a REST backend link mywebsite/guests, which returns list of guests. In the front end, I want to display the guests as links. Here's the code
for(guest of guests) {
$('#guest_list').append('<a onclick="showGuest(' + guest.id + ')">' + guest.name + '</a><br>')
}
function showGuest(id) {
console.log(id)
...
}
I should mention that guest.id is a string.
The console always print undefined. My question, how can I add these links with String parameters?
for(guest of guests) {
$('#guest_list').append('<a onclick="showGuest(this)" data-id='+guest.id+'>' + guest.name + '</a><br>')
}
function showGuest(this) {
console.log($(this).data('id'))
}
The main issue is that you are trying to access the property of dynamically bound DOM elements in your showGuest(id) function. You should use the onClick function in the following way-
var guests = [{"id":1, "name":"John Doe"},
{"id":2, "name":"David Jones"}];
for(guest of guests) {
$('#guest_list').append('<a class="guest" data-id="'+guest.id+'">' + guest.name + '</a><br>');
}
$('#guest_list').on('click', 'a.guest', function() {
var id = $(this).attr('data-id');
$('.message').text('').append("Clicked guest with ID: "+id);
});
Working JSFiddle here - https://jsfiddle.net/2dkpsve8/
Hope this helps!
The way to approach this problem depends on the format and content of the guests variable. If you started with this object:
var guests = {
'123': {id: 123, name: 'joe'},
'234': {id: 234, name: 'jane'}
};
Then key would be "123" and "234" in the following loop, and the object values would be guests[key]:
for(var key in guests) {
$('#guest_list').append('<a onclick="showGuest(' + guests[key].id + ')">' + guests[key].name + '</a><br>')
}
function showGuest(id) {
console.log(id)
...
}
But if you're already using jQuery, take a look at jQuery.each for another looping option.
On the other hand, if guests is an array, as in:
var guests = [
{id:"123", name:"joe"},
{id:"234", name:"jane"}
];
then you will just want to use something like:
for(var i=0; i < guests.length; i++) {
// id is guests[i].id
// name is guests[i].name
}
Amazingly,
$('#guest_list').append('<a onclick="showGuest(' + "guest.id" + ')">' + guest.name + '</a><br>')
works fine! I don't know way. "guest.id" is replaced by the actual id of guest.
Related
Im having some trouble figuring this out. I have a database which has users on it and I want to display each user on the page dynamically using jquery.
Ive just thrown some user data objects in a array and im trying to call for each user object in the array to display as a list item on the page
html
<h1>List</h1>
<ul id="list">
</ul>
javascript
var user = [
{
username: alex,
age: 20
},
{
username: james,
age: 20
}
]
function addUser() {
var username = user.username;
var age = user.age
var $user = $("<li>" + username + "</li>");
var $age = $("<li>" + age + "</li>");
$("#list").append($user + " " + $age);
}
$.each(user, addUser());
Your mistake is very simple. You have to replace addUser() by addUser when you use the $.each method. There are also mistakes when you use the.append method. Try this code:
var user = [
{
username: "alex",
age: 20
},
{
username: "james",
age: 20
}
];
function addUser(theCase, value) {
var username = value.username;
var age = value.age;
var user = '<li> ' + username; // Use a simple string, it's better and faster!
var age = age + ' </li>';
$("#list").append(user + " " + age);
}
$.each(user, addUser);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<h1>List</h1>
<ul id="list">
</ul>
Here you are using a callback. If you want more details about callbacks consult the MDN's documentation.
There are also several errors on .each method or .append method. Consult the documentation.
The .each method call your callback for each case on your array user. This method also provide you, in your callback, the index and the value of the case witch is treated.
Can you please check page: https://jsfiddle.net/rxcz73x9/2/
var user = [{
username: "alex", // use string
age: 20
}, {
username: "james", // use string
age: 20
}];
function addUser(idx, user) {
var username = user.username;
var age = user.age
var $user = $("<li>" + username + "</li>");
var $age = $("<li>" + age + "</li>");
$("#list").append($user).append($age); // use append for each node
}
$.each(user, addUser); // use function name instead of addUser()
I've added comment that could help you with example above.
When you pass a callback to the jQuery each function, what happens is that the callback is going to be invoked with every element in your user array.
Check the arguments that jQuery.each passes to the callback. The callback function signature should expect the index and the value of the element in that index.
For example:
var users = user = [
{
username: alex,
age: 20
},
{
username: james,
age: 20
}
];
function addUser(index, user) {
// do what you want and in the end
$('#list').append(/* an <li> element */);
};
// Now pass the function as a callback, but don't invoke it.
$.each(users, addUser);
We're trying to run through a collection of objects with properties (key: value)'s and write it to the dom.
var productContent = {
item1: {
description: "description 1",
price: 1,
URL: "something1.com",
},
item2: {
description: "description 2",
price: 2,
URL: "something2.com",
},
We've tried a few different types of code, such as:
var productInfo;
var insertProduct = document.getElementById("productList");
for (var i in productContent) {
console.log(productContent[i]);
productInfo += productContent[i];
}
insertProduct.innerHTML = productInfo;
Nothing seems to be working. Any thoughts on how to approach this? We've been able to get properties shown in the console but not much else.
Your first codeblock has a syntax error. The productContent object is missing a closing curly brace: }.
You also have a comma after the last property instead of only between properties.
You should use the JS console in your browser's developer tools to debug this.
You have some errors in your script, you can start with following:
var htmlValue = '';
for (var productKey in productContent) {
var product = productContent[productKey];
htmlValue += 'description: ' + product.description + '<br>';
htmlValue += 'price: ' + product.price + '<br>';
htmlValue += 'url: ' + product.URL + '<br><br>';
}
insertProduct.innerHTML = htmlValue;
Errors:
1.
for (var i in productContent) {
This is just a strong suggestion, but you should change i to something meaningful for the context, such as key since you are iterating over object properties. Naming properly your variables will help you spot errors in your code.
2.
productInfo += productContent[i]
This is not the proper way to concatenate object values. First iteration and it will be "undefined[object Object]".
3.
insertProduct.innerHTML = productInfo;
What are you even trying to do here? You can't just put in element an object. You must put as code and formatted the way you want.
I see there is a problem to get a String name from JSON object's name.
I need to parse this kind on JSON response from server.
var response = {
hopaopGmailsjIpW: {
GmailsjIpW_totalEmails_count: 133,
GmailsjIpW_state: 1
},
hopaopGmail4y4yu: {
Gmail4y4yu_totalEmails_count: 156,
Gmail4y4yu_state: 1
}
}
It is not an Array, but the object with inner objects.
i need to parse an inner ojects name and add additional values to each object.
i want be able to do something like this:
for(var i =0; i < response.length; i++){
response[i].username = parseUsernameFromString(response[i]);
response[i].service = parseServiceFromString(response[i]);
response[i].id = parseIdString(response[i]);
}
(and also state for each task)
So the question is:
What is the best way to make it?
UPDATE
this is exactly what i have for now:
for(var key in response){
if(stringContains(response[key], "Gmail")) { response[key].service = "Gmail";}
console.log("task name: "+ response[key].service);
}
function stringContains(originalString, searchString){
if(originalString.indexOf(searchString) > -1){
return true
}
else return false;
}
For walking through Objects, you need to use for ... in loop.
The real problem is: There's a , missing in your code. See the fixed working snippet:
Snippet
var response_Parsed = {
hopaopGmailsjIpW: {
GmailsjIpW_totalEmails_count: 133,
GmailsjIpW_state: 1,
service: 'Gmail',
username: 'hopaop',
id: 'sjIpW'
},
hopaopGmail4y4yu: {
Gmail4y4yu_totalEmails_count: 156,
Gmail4y4yu_state: 1,
service: 'Gmail',
username: 'hopaop',
id: '4y4yu'
}
};
for (id in response_Parsed) {
console.log("----");
if (id.indexOf("Gmail") > -1) {
console.log("We have Gmail: " + id);
console.log("UniqueName: " + id.replace("hopaopGmail", ""));
console.log("Username: " + response_Parsed[id].username);
console.log("Email Count: " + response_Parsed[id][id.replace("hopaop", "") + "_totalEmails_count"]);
}
else
console.log("We don't have Gmail: " + id);
}
And also the right way to enumerate the through the keys of the objects, is by using Object.keys.
If the response is a String like you wrote, you should first parse the JSON-String into an Object (if you're using a library like jQuery, it's probably already a JSON, as this conversion is done by jQuery automatically):
var obj = JSON.parse(responseString);
Afterwards you may iterate through it like posted above:
for (var key in obj) {
console.log("key", key, "value", obj[key]);
}
currently working with jquery object
the object contains data like
data[0]={CustUserID: 31, FirstName: "System12", LastName: "Administrator", CustUserName: "SysAdmin"}
this object contains n number of records,and we get the length using data.length
and also each object each record contains different type of keys and n number of keys with value
so now i am trying to get each key name and value name from each record and need to show on page.
on html view:
CustUserID=31
FirstName=System12
LastName=Administrator
CustUserName=SysAdmin
the code i wrote for this is
var data="";
for(var i=0;i<data.length;i++)
{
data= data+"</br>CustUserID="+data[i].CustUserID+
"</br>FirstName="+data[i].FirstName+
"</br>LastName="+data[i].LastName+
"</br>CustUserName="+data[i].CustUserName;
}
$("#DivData").html(data);
but i stucked when data keys are dynamically changing according to user requirment so at that i am facing problem to get data, so i need to get key names and data should be looped dynamically.
please help me...
thank you guys..
You can use jQuery .each()
var data_result = '';
//first loop will go trough all data array elements
$.each(data, function(key, data_element){
// second loop will go trough all object keys
$.each(data_element, function(key, value){
data_result += '<br/>' + key + '= ' + value);
});
});
$("#DivData").html(data_result );
You can do this without jQuery too
var data = {
CustUserID: 31,
FirstName: "System12",
LastName: "Administrator",
CustUserName: "SysAdmin"
};
var dataHtml = '';
for (var p in data) {
if (data.hasOwnProperty(p)) {
dataHtml += '<br/>' + p + "=" + data[p];
}
}
$("#DivData").html(dataHtml);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div id="DivData"></div>
var mydata = Array(), result;
mydata[0]={CustUserID: 31, FirstName: "System12", LastName: "Administrator", CustUserName: "SysAdmin"};
for (var key in mydata[0]){
var obj = mydata[0][key];
result += '<br/>'+key+'='+obj;
}
jQuery("#myid").html(result);
As desired Mongoose returns the following data:
[Object]
0: Object
thread_history: Array[12]
0: Object
__v: 0
_id: "52c5be11be9931f90b000002"
body: "thread message"
uid: "maarten"
__proto__: Object
1: Object
2: Object
3: Object
I emit this data using socket.io and then I try to convert the data to html.
Normally I would use the following for loop to convert the emitted data to html
socket.on('thread_history', function (thread_data) {
if(thread_data.thread_history) {
threads_log.push(thread_data);
console.log(threads_log);
var html = '';
for (var i = 0; i < threads_log.length; i++) {
html += '<div class="thread_wrapper">' + (threads_log[i].uid ? threads_log[i].uid : 'Server') + ' - ' + threads_log[i].body + '</div>';
}
thread_content.innerHTML = html;
thread_content.scrollTop = content.scrollHeight;
}
else {
console.log("There is a problem: ", thread_data);
}
});
Of course this doesn't work for the mongoose returned data.
I'm simply not able to access the objects, can someone assist me with this? And what am I doing wrong?
It looks that you are looping through the wrong object, you are pushing "thread_data" and assuming to loop through "thread_data.thread_history".
Perhaps change line where you are pushing data to:
threads_log.push(thread_data.thread_history)
Otherwise if you need the whole tread_data in your log, inside your loop do:
threads_log[i].thread_history.body
Using jQuery I came up with a really nice and clean solution.
socket.on('thread_history', function (thread_data) {
if(thread_data.thread_history) {
threads_log.push(thread_data.thread_history);
console.log(threads_log);
var html = '';
// jquery each the results
$.each(thread_data.thread_history, function(){
html += '<div class="thread_wrapper">' + this.uid + " - " + this.body + '</div>';
});
thread_content.innerHTML = html;
thread_content.scrollTop = content.scrollHeight;
}