How to use an object property as a function argument? - javascript

SOLUTION
Thanks to vadim. I had to change months[i].anArray[b] to months[i][anArray][b]
I have an array of months, which contains an object for each month. Each month has a number of properties, including arrays, for example:
months[0].consumptionPerHour returns 24 values which can be accessed with months[0].consumptionPerHour[0-23]
I am attempting to create a function which creates a table, having the name of the table and the name of the array I wish to access as arguments with the function, like so:
function tableMaker(tableName, anArray) {
$("#outputs").append(
"<table id='table" + totalTables + "'>"
"<tr id='header" + totalTables + "'><td>" + tableName + "</td>"
);
for(i=0;i<12;i++) {
$("#header" + totalTables).append("<td>" + months[i].shortName + "</td>");
}
for(b=0;b<24;b++) {
$("#table" + totalTables).append(
"<tr id='table" + totalTables + "row" + b + "'><td>" + hours[b] + "</td>"
);
for(i=0;i<12;i++) {
$("#table" + totalTables + "row" + b).append("<td>" + months[i].anArray[b] + "</td>");
}
}
}
For some reason, if I pass a property name that I know exists as an argument, for example, tableMaker('Consumption', consumptionPerHour), it simply returns the following:
Uncaught ReferenceError: consumptionPerHour is not defined
at <anonymous>:1:22
However, this is returned via console:
months[0].consumptionPerHour
(24) [0.1567002086212712, 0.1567118400503239, ...]
months[0].consumptionPerHour[0]
0.1567002086212712

To access an object property using a variable you need to use [] notation and the variable needs to be a string
So I think what you want is
tableMaker('Consumption', 'consumptionPerHour')
Then in function use:
months[i][anArray][b]

It looks like the 'consumptionPerHour' is an array within the 'months' array. And it also looks like you have access to the months array in the function without having to pass it in as a parameter. So the function would look something like this:
function tableMaker(tableName) {
$("#outputs").append(
"<table id='table" + totalTables + "'>"
"<tr id='header" + totalTables + "'><td>" + tableName + "</td>"
);
for(i=0;i<12;i++) {
$("#header" + totalTables).append("<td>" + months[i].shortName + "</td>");
}
for(b=0;b<24;b++) {
$("#table" + totalTables).append(
"<tr id='table" + totalTables + "row" + b + "'><td>" + hours[b] + "</td>"
);
for(i=0;i<12;i++) {
$("#table" + totalTables + "row" + b).append("<td>" + months[i].consumptionPerHour[b] + "</td>");
}
}
}

Related

Table in jQuery with toggable row

I have a table with the list of orders in my ecommerce site. I would like another line to appear with the order details by clicking on each line.
I don't understand how to write the function.
Here is how i wrote the table row:
$("#tbody").append("<tr id='riga" + i + "'><th scope='row'>" + idordine
+ "</th><td>" + data + "</td><td>" + prezzoTotale
+ "€</td><td> <button id='button_" + i
+ "')>Dettagli</button></tr><tr id='orderdetail_" + i
+ "' style='display:none;'>"
+ "<th scope='row'> ciao </th><td>ciao2</td><td>ciao2</td><td>ciao2</td></tr>"
);
and the function i wrote is:
for (var i = 0; i < ordini.length; i++) {
$("#button_" + i).click(function(i) {
$("#orderdetail_" + i).toggle("slow");
});
}
the variable i in $("#orderdetail_"+i) doesn't work. How can i do it?
Thanks all.
There's no need to link button_i with orderdetail_i, you can use relative navigation, in this case a relatively simple:
$(this).closest("tr").next()
To facilitate the event handler, I've added togglebutton class to each button and used that in a single selector.
Updated code:
// setup some example data
for (var i = 1;i<10; ++i) {
$("tbody").append("<tr id='riga" + i + "'><th scope='row'>" + "idordine"
+ "</th><td>" + "data" + "</td><td>" + "prezzoTotale"
+ "€</td><td> <button class='togglebutton' id='button_" + i
+ "')>Dettagli</button></tr><tr id='orderdetail_" + i
+ "' style='display:none;'>"
+ "<th scope='row'> ciao </th><td>ciao" + i + "</td><td>ciao" + i + "</td><td>ciao" + i + "</td></tr>"
);
}
// handle toggle
$("button.togglebutton").click(function() {
$(this).closest("tr").next().toggle();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody>
</tbody>
<table>

Javascript Append Function, Need to build a loop

I have a .php file where I am using both HTML and JavaScript to display items from my database. I have a JavaScript append function that is creating cards where each item is display. On my cards, I have a button that will expand the card to show product history. Some products have more history than others so the expansion needs to be dynamic. The historical data is being pulled from database and is initially in a php array. I originally was going to institute php into the javascript append function but I could not figure out how to set the JavaScript index variable 'I' to my php index. So I want to just stay with JavaScript. But I don't know how to write a loop in the middle of this append function that will loop through the historical array and populate the expansion. Below is what I am attempting. I took out a lot of the lines in the append function but you can see what I am trying to do.
function get_products() {
clear_cards();
$.each(productNumbers,
function(i, value) {
$('.main_card_shell').append(
"<div class='card_content card_style' id='card" + i + "'>" +
"<div id='card_tab2" + i + "' class='tabcontent' data-tab='tab-name2'>" +
"<div class='details_tables'>" +
"<table>" +
"<tr>" +
"<th>Item Type</th>" +
"<th>Painted</th>" +
"<th>Last Sold" +
"<a id='_close_tab" + i + "' class='tablinks tab_override' onclick=\"openCity(event,'card_tab4" + i + "')\">" +
"<i class='large angle up icon'></i>" +
"</a>" +
"</th>" +
"</tr>" +
"<tr>" +
var itemdatesplit = itemdate[i].split("$$");
var itemtypesplit = itermtype[i].split("$$");
var itemsplit = item[i].split("$$");
var arraylength = itemsplit.length;
var counter = 0;
while(counter < arraylength)
{
+ "<td>" + itemtypesplit[counter] + "</td>" +
+ "<td>" + itemdatesplit[counter] + "</td>" +
counter = counter + 1;
}
+
"</tr>" +
"</table>" +
"</div>" +
"</div>" +
Please help. I had it working with PHP inserted in, but I just couldn't figure out how to set it to a PHP variable.
Place this code into a function:
function getSomething(i) {
var html = '';
var itemdatesplit = itemdate[i].split("$$");
var itemtypesplit = itermtype[i].split("$$");
var itemsplit = item[i].split("$$");
var arraylength = itemsplit.length;
var counter = 0;
while(counter < arraylength) {
html += "<td>" + itemtypesplit[counter] + "</td>";
html += "<td>" + itemdatesplit[counter] + "</td>";
counter = counter + 1;
}
return html;
}
And then use it in your HTML building block:
'<some html>' + getSomething(i) + '<some other html>'

Unable to append, to an html element, values of an array of objects passed as parameter to jQuery each

I have an array of objects, that I loop through using $.each and try and append the array object value to an <li>.
Please find the jQuery below
$(".sidebar").empty().append("<div>"+
"<h5>Student Info</h5>" +
"<ul>" +
$.each(studentInfo, function (index, value) {
console.log(value.studentName + " :studentName ");//prints the student name in the browser console
"<li>Student No " + index + "</li>"
"<li>Name - " + value.studentName + "</li>"
"<li>Contact - " + value.contact + "</li>"
"<li>DOB - " + value.dob + "</li>"
"<li>PAN - " + value.PANNo + "</li>"
"<li>Address - " + value.postalAddress + "</li>"
}) +
"</ul>" +
"</div>")
The above function only prints [object Object],[object Object] in the <li>. I have tried stringifying the array, parsing the array, different ways of appending json objects but its still the same.
The array of objects that I am trying to loop through
var studentInfo = [
{
"studentName":"abc",
"contact":"123456789",
"dob":"22-05-1994",
"PANNo":"ABCDEF1234",
"postalAddress":"chandigarh, sector - 18"
},
{
"studentName":"xyz",
"contact":"123456987",
"dob":"22-05-1994",
"PANNo":"ABCDEF4321",
"postalAddress":"chandigarh, sector - 78"
}
]
I have been at it for hours but unable to figure out what I am doing wrong, I am still new at jQuery and its ways. Any help is really appreciated. Thanks.
jQuery $.each() is not meant to return a string. you use it to treat each object separately. You can't just parse it as string expression.
You will need to split your code into multiple parts.
Part 1: clear .sidebar and prep it for the menu items.
Part 2: build a string items that contain all the object values parsed into HTML list-items.
Part 3: append the string to the '.sidebar'
var studentInfo = [
{
"studentName":"abc",
"contact":"123456789",
"dob":"22-05-1994",
"PANNo":"ABCDEF1234",
"postalAddress":"chandigarh, sector - 18"
},
{
"studentName":"xyz",
"contact":"123456987",
"dob":"22-05-1994",
"PANNo":"ABCDEF4321",
"postalAddress":"chandigarh, sector - 78"
}
];
var items = "";
$.each(studentInfo, function (index, value) {
console.log(value.studentName + " :studentName ");
items += "<li>Student No " + index + "</li>"
+ "<li>Name - " + value.studentName + "</li>"
+ "<li>Contact - " + value.contact + "</li>"
+ "<li>DOB - " + value.dob + "</li>"
+ "<li>PAN - " + value.PANNo + "</li>"
+ "<li>Address - " + value.postalAddress + "</li>"
+ "<hr>" ;
})
+
$(".sidebar").empty().append("<div>"+
"<h5>Student Info</h5>" +
"<ul>" + items + "</ul></div>");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="sidebar"></div>

Possible to add a loop while appending to the DOM?

I'm appending some information to the DOM, but realized that some of the information I need is nested within an object. When I do the below bit of code, the part within the loop returns as undefined. Is there a way to iterate over and pull out this information so that I can append it to my page:
function placeOnPage(allStopsWithRoutes){
allStopsWithRoutes.forEach(function(stop){
$('#stops').append("Stop: " + stop.crossStreets + "<br>" +
// LOOP HERE
stop.routes.forEach(function(route){
"Bus Name: " + busName + "<br>" +
"Stops Away: " + stopsAway + "<br>" +
"Destination: " + destination + "<p>"
});
// END LOOP
);
});
}
I don't think strings can be concatenated that way. Change your approach to concatenate before hand and store it in a variable. Then append the variable
function placeOnPage(allStopsWithRoutes) {
allStopsWithRoutes.forEach(function(stop) {
var concatenatedStr = '';
stop.routes.forEach(function(route) {
concatenatedStr += ("Bus Name: " + busName + "<br>" +
"Stops Away: " + stopsAway + "<br>" +
"Destination: " + destination + "<p>");
});
$('#stops').append("Stop: " + stop.crossStreets + "<br>" + concatenatedStr);
});
}

jquery val() coming up as blank after .each()

I'm iterating with
function editRow(a) {
$("td").each(function () {
alert($(this).val())
});
}
which iterates through
$("tbody").append(
"<tr id = '" + trId + "'>" +
"<td name = 'nameRow' id = 'name" + idCt + "' value = 'test' > <strong>" + name + "</strong> </td>" +
"<td name = 'maxRow' id = 'max" + idCt + "' value = '" + max + "'>" + max + "</td>" +
"<td name = 'setRow' id = 'sets" + idCt + "' value = '" + sets + "'>" + sets + "</td>" +
"<td name = 'repRow' id = 'reps" + idCt + "' value = '" + reps + "'>" + reps + "</td>" +
"<td name = 'restRow' id = 'rest" + idCt + "' value = '" + rest + "'>" + rest + "</td>" +
"<td id = 'link" + idCt + "'><a href='#' onclick='return deleteRow(" + trId + ");' >Remove</a>" +
" | <a href='#' onclick='return editRow(" + idCt + ");'>Edit</a></td>" +
"</tr>"
);
The alter($(this).val()) is coming up the correct amount of times, but it is always just blank (not undefined)).
I know it's not that readable, but does anyone see an error?
Thanks!
.val() is a method which is only defined for input elements. Normal HTML elements don't have a value. You should use .html() or .text() to get the content of those elements
function editRow(a) {
$("td").each(function () {
alert($(this).text())
});
}
You should define non-standard attributes (like value for <td>) using the data- prefix
<td data-value="whatever">...</td>
Then you can use jQuery's .data() method to access those attributes
var tdDataValue = $(this).data('value');
The problem is that "td" - elements haven't values. They have inner HMTL. If you want to get td's content, you need to use $(this).html()
function editRow(a) {
$("td").each(function () {
alert($(this).html())
});
}
The val method is usually reserved for input tags. For td you can do either:
$(this).text();
or
$(this).attr('value');
simply try something like this
function editRow(a) {
$("td").each(function () {
alert(this.innerText);// reading inner text
alert($(this).attr('value'));// reading value attribute
});
}

Categories