How to Select an Element of An Appended Table With Jquery - javascript

I built a table by using .append on a div (id = calendarData) that is in the html:
$j('#calendarData').append(
'<table class="grid" id="calendar" href="#" style="max-width:1200px"><th colspan="7" align=""center">' +
months[currentMonth] + " " + currentYear + '</div></th><tbody>'+
'<tr><td>Sun</td><td>Mon</td><td>Tues</td><td>Wed</td><td>Thurs</td><td>Fri</td><td>Sat</td>'
);
Then I added all of the cells to the table:
for(var i=0; i<6; i++){
$j('#calendar > tbody:last-child').append(
'</tr><tr>'
);
for(var j=0;j<7;j++){
if(inMonth == 0 && day > getDaysInMonth(startDate.getMonth()-1)){
day = 1;
inMonth = 1;
}
else if(inMonth == 1 && day > getDaysInMonth(startDate.getMonth())){
day = 1;
inMonth == 2;
}
$j('#calendar > tbody:last-child').append(
'<td class="square">' + day + '</td>'
);
day++;
}
}
$j('#calendarData > tbody:last-child').append(
'</tr></tbody></table>'
);
After this I need to go back and select each td and give it a color if that day is active(determined in a later function) but every time I try to grab it the system comes back with undefined.
Everything from:
$j('#calendarData tbody:last-child').style.backgroundColor = 'green';
to
var t = document.getElementById("calendar");
var r = t.getElementsByTagName("tr")[0];
var d = r.getElementsByTagName("td")[0];
d.style.backgroundColor ='green';
Every time it throws an Error 'Cannot change Background Color of Undefined"
Any ideas what I am doing wrong?

Not sure why it's doubling-up the dates in my example, but that's not the point.
To style the injected HTML class after the fact, you can either add the class ahead of time to the CSS, or you can use jQuery .css() to add the styling via jQuery:
setTimeout(function(){
$('.active').css({'color':'maroon','font-weight':'bold','background':'yellow'});
},3000);
$('#calendarData').append('\
<table class="grid" id="calendar" href="#" style="max-width:1200px">\
<th colspan="7" align=""center">' +'June'+ "" + '2016' + '</div></th><tbody>\
<tr><td>Sun</td><td>Mon</td><td>Tues</td><td>Wed</td><td>Thurs</td><td>Fri</td><td>Sat</td></tr>'
);
setTimeout(function(){
//This mimics your generated / injected code
$('#calendarData > table > tbody').append('\
<tr><td class="square">1</td><td class="square">2</td><td class="square">3</td><td class="square">4</td><td class="square">5</td><td class="square">6</td><td class="square">7</td></tr>\
<tr><td class="square">8</td><td class="square">9</td><td class="square">10</td><td class="square active">11</td><td class="square">12</td><td class="square">13</td><td class="square">14</td></tr>\
<tr><td class="square">15</td><td class="square">16</td><td class="square">17</td><td class="square">18</td><td class="square">19</td><td class="square">20</td><td class="square">21</td></tr>\
<tr><td class="square">22</td><td class="square">23</td><td class="square">24</td><td class="square">25</td><td class="square">26</td><td class="square">27</td><td class="square">28</td></tr>\
</tbody></table>'
);
},1500);
.square{text-align:center;}
.active{font-style:italic;font-size:larger;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="calendarData"></div>

Related

How to insert multiple HTML elements using jQuery

I have a webpage that is taking data from the Yahoo! Weather API. I am using this query. I would like to build a table using jQuery that inserts elements with IDs. Here is my current code:
$.get("https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22canberra%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys", function(data) {
$("#title").append(data.query.results.channel.title);
$("#sunrise").append(data.query.results.channel.astronomy.sunrise);
$("#sunset").append(data.query.results.channel.astronomy.sunset);
$("#title-2").append(data.query.results.channel.item.title);
for (var i = 0; i < 10; i += 1) {
var newRow = $("<tr></tr>").attr("id", "row-" + (i + 1));
var newDate = $("<td></td>").attr("id", "date-" + (i + 1));
var newMin = $("<td></td>").attr("id", "min-" + (i + 1));
var newMax = $("<td></td>").attr("id", "max-" + (i + 1));
var newConditions = $("<td></td>").attr("id", "conditions-" + (i + 1));
$("#weather").append(newRow);
$("#row-" + (i + 1)).append(newDate, newMin, newMax, newConditions);
$("#date-" + (i + 1)).append(data.query.results.channel.item.forecast[i].day + " " + data.query.results.channel.item.forecast[i].date);
$("#min-" + (i + 1)).append((Math.floor(((data.query.results.channel.item.forecast[i].low) - 32) / 1.8)) + "°C");
$("#max-" + (i + 1)).append((Math.floor(((data.query.results.channel.item.forecast[i].high) - 32) / 1.8)) + "°C");
$("#conditions-" + (i + 1)).append(data.query.results.channel.item.forecast[i].text);
}
$("#lastBuild").append(data.query.results.channel.lastBuildDate);
}, "json");
div#main {
width: 595px;
}
table#weather {
border-collapse: collapse;
width: 595px;
}
table#headers {
width: 595px;
}
td,
th {
width: 148.75px;
text-align: center;
}
tr {
height: 28px;
}
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<div id="main">
<h1 id="title"></h1>
<ul id="sun">
<li id="sunrise"><strong>Sunrise: </strong></li>
<li id="sunset"><strong>Sunset: </strong></li>
</ul>
<h2 id="title-2"></h2>
<table id="headers">
<tr>
<th id="date">Date</th>
<th id="min">Min</th>
<th id="max">Max</th>
<th id="conditions">Conditions</th>
</tr>
</table>
<table id="weather" border="1"></table>
<br />
</div>
<em id="lastBuild">Data last built at: </em>
My question is this:
Am I going about the correct way of doing this? It works, but it might just be an autofill by the interpreter (like leaving off semicolons). Is this right, and if not, how can I fix it? All help appreciated.
Currently it looks good to me. If your page will only ever query the information once, then it should be fine as long as it is working now. If you want to allow multiple queries (like allowing the user to select a date and press a button to retrieve information of another day), you might want to empty the relevant elements before appending new items to them.

Modifying <img src style="visibility"> through JavaScript

I'm building a memory game in HTML & JS where you guess 2 different images and try to pick 2 same ones.
I'm stuck with putting an onclick function to a hidden image.
Here is my code so ill try to explain better...
var table = '';
for(var i = 0; i < 4; i++){
table += '<tr>';
for(var j = 0; j < 3; j++){
table += '<td align="center"><img src="./pics/image_part_00' + Math.floor((Math.random() * 6) + 1) + '.jpg";" width="100px"" onclick="clicked(this);" style="visibility: hidden;"></td>';
}
table += '</tr>';
}
document.getElementById('theGame').innerHTML = '<table border=1 cellpadding="10" class="tabela1">' + table + '</table>'
Now what im trying to do is to overwrite that visibility: hidden; so the image is visible when clicked....
And here is the function
function clicked(element){
element.style.visibility = "visible";
}
but it doesn't work because with that element.style.visibility im changing the visibility of a table cell.
Anyone got a solution? I'm probably missing something and can't figure it...
NOTE: It's a school assignment so it has to be in a table.
Here is a some fixed javascript. when you catch onclick event, it won't work on hidden elements. So I move event listener onto td:
var table = '';
for(var i = 0; i < 4; i++){
table += '<tr>';
for(var j = 0; j < 3; j++){
table += '<td align="center" onclick="click_it(this)">
<img src="./pics/image_part_00' + Math.floor((Math.random() * 6) + 1) + '.jpg"
width="100px" style="visibility: hidden"></td>';
}
table += '</tr>';
}
document.getElementById('theGame').innerHTML = '<table border=1 cellpadding="10" class="tabela1">' + table + '</table>';
function click_it(cell){
var image = cell.children[0];
image.style.visibility = 'visible';
}
You can search for the img child of the table cell
var child = element.childNodes;
The var child will return an array of elements, then you just need to access to the position that the is, and change the visibility attribute:
child[1].style.visibility = "visible";
You can try below,
just played a trick to match element id dynamically
to make it visible.
Added on click to td instead of image.
added id to image.
here is the code
<div id="theGame">
var table = '';
for (var i = 0; i < 4; i++) {
table += '<tr>';
for (var j = 0; j < 3; j++) {
table += '<td align="center" onclick="clicked(' + j + ')"> <img id=img_' + j + ' src="./pics/image_part_00' + Math.floor((Math.random() * 6) + 1) + '.jpg;" width="100px" style="visibility: hidden;"> </td>';
}
table += '</tr>';
}
document.getElementById('theGame').innerHTML = '<table border=1 cellpadding="10" class="tabela1">' + table + '</table>'
function clicked(element) {
document.getElementById('img_' + element).style.visibility = "visible";
}

JQuery not grabbing HTML data

I have the following HTML table displayed on my webpage.
<div class="timecard">
<table class="misc_items timecard_list" border="0" cellpadding="2" cellspacing="0" style="margin:0 auto;">
<tbody>
<tr class="display_row odd">
<td align="left" class="job_code" style="color:#000099">2400-Orchard</td>
<td align="right">9:47am</td>
<td align="right">5/19/2014</td>
<td align="right" class="hrs">01:00</td>
</tr>
<tr class="display_even odd">
<td align="left" class="job_code" style="color:#000099">1500-Emerald</td>
<td align="right">12:37am</td>
<td align="right">5/17/2014</td>
<td align="right" class="hrs">0:30</td>
</tr>
</tbody>
</table>
</div>
<div id="total"></div>
Then I have the following jquery script that grabs the total times for each job_code and adds them up and displays them. However, it does not seem to be working properly. It isn't displaying the totals added up by the jQuery statement underneath the HTML table as it should be.
$(document).ready(function () {
var timeString = $(this).next('td.hrs').text();
var components = timeString.split(':');
var seconds = components[1] ? parseInt(components[1], 10) : 0;
var hrs = parseInt(components[0], 10) + seconds / 60;
total += hrs;
var temp = [];
$('.job_code').each(function (index, element) {
var text = $(this).text();
temp.push(text);
});
// remove duplicates
var job_code = [];
$.each(temp, function (index, element) {
if ($.inArray(element, job_code) === -1) job_code.push(element);
});
var sum = {};
$.each(job_code, function (index, element) {
var total = 0;
$('.job_code:contains(' + element + ')').each(function (key, value) {
var timeString = $(this).siblings('td.hrs').text();
var components = timeString.split(':');
var seconds = components[1] ? parseInt(components[1], 10) : 0;
var hrs = parseInt(components[0], 10) + seconds / 60;
total += hrs;
sum[index] = {
'job_code': element,
'total': total
};
});
});
console.log(sum);
$.each(sum, function (index, element) {
$('#total').append('<p>Total for ' + element.job_code + ': ' + element.total + '</p>');
});
});
http://jsfiddle.net/2D5fb/1/
Any ideas are greatly appreciated. Thanks.
Aside from total not being defined, change:
var timeString = $(this).next('td.hrs').text();
to
var timeString = $(this).siblings('td.hrs').text();
.next() literally only looks at the next element and td.hrs isn't the next one. .siblings() however will run through all the siblings.
jsFiddle example

Dynamically add <td>'s to a table

I am trying to create a table of 30 days of dates, starting from today.
right now I have this working, but it is being returned as a string.
I want to add a <td> with each date returned to my table.
My code is this
HTML
<table>
<tbody>
<tr>
<td></td> <!-- Add Each Date here -->
</tr>
</tbody>
</table>
JS
var date = moment(),
begin = moment(date).startOf('week').isoWeekday(1);
var str = "";
for (var i=0; i<30; i++) {
str += begin.format("MMM Do") + '<br>';
begin.add('days', 1);
}
// Would like to add date to each <td> and add <td> to the table
document.body.innerHTML = str;
DEMO
Just need slight addition to your existing code see below,
var date = moment(),
begin = moment(date).startOf('week').isoWeekday(1);
var str = [];
for (var i=0; i<30; i++) {
str.push('<td>' + begin.format("MMM Do") + '</td>');
begin.add('days', 1);
}
$('#myTable tbody').append('<tr>' + str.join('') + '</tr>');
DEMO: http://jsfiddle.net/wzdr2/
This should work:
for (var i=0; i<30; i++) {
$("table tr").append("<td>" + begin.format("MMM Do") + "</td>");
begin.add('days', 1);
}
Try not to append to DOM each time, it'l make it slower and inefficient especially if you have too many items to be appended. Instead add them up and append in the end.
var str = "", $tds= [];
for (var i=0; i<30; i++) {
$tds.push('<td>' + begin.format("MMM Do") + '</td>'); //push the tds to the temp array
begin.add('days', 1);
}
// Would like to add date to each <td> and add <td> to the table
$('table tr').append($tds); //append in the end
Demo
You could append them as you go. Like so...
http://jsfiddle.net/jzKMS/
for (var i=0; i<30; i++) {
$('#dates tbody').append('<tr><td>' + begin.format("MMM Do") + '</td></tr>');
begin.add('days', 1);
}
Or, for faster running, build your elements first and append once at the end.

javascript, calendar

I would like to ask if there's anyway I can 'shift' the calender to the right side of the page? Because I realized that it can only be displayed on the left hand side. I do not really know how to 'shift' it to the right hand side... Neither do I know how to put css in to do it.
Here's the code to make the calendar...
<script type="text/javascript">
// SET ARRAYS
var day_of_week = new Array('Sun','Mon','Tue','Wed','Thu','Fri','Sat');
var month_of_year = new Array('January','February','March','April','May','June','July','August','September','October','November','December');
// DECLARE AND INITIALIZE VARIABLES
var Calendar = new Date();
var year = Calendar.getFullYear(); // Returns year
var month = Calendar.getMonth(); // Returns month (0-11)
var today = Calendar.getDate(); // Returns day (1-31)
var weekday = Calendar.getDay(); // Returns day (1-31)
var DAYS_OF_WEEK = 7; // "constant" for number of days in a week
var DAYS_OF_MONTH = 31; // "constant" for number of days in a month
var cal; // Used for printing
Calendar.setDate(1); // Start the calendar day at '1'
Calendar.setMonth(month); // Start the calendar month at now
/* VARIABLES FOR FORMATTING
NOTE: You can format the 'BORDER', 'BGCOLOR', 'CELLPADDING', 'BORDERCOLOR'
tags to customize your caledanr's look. */
var TR_start = '<TR>';
var TR_end = '</TR>';
var highlight_start = '<TD WIDTH="10"><TABLE CELLSPACING=0 BORDER=1 BGCOLOR=DEDEFF BORDERCOLOR=CCCCCC><TR><TD WIDTH=5><B><CENTER>';
var highlight_end = '</CENTER></TD></TR></TABLE></B>';
var TD_start = '<TD WIDTH="1"><CENTER>';
var TD_end = '</CENTER></TD>';
/* BEGIN CODE FOR CALENDAR
NOTE: You can format the 'BORDER', 'BGCOLOR', 'CELLPADDING', 'BORDERCOLOR'
tags to customize your calendar's look.*/
cal = '<TABLE BORDER=1 CELLSPACING=0 CELLPADDING=0 BORDERCOLOR=BBBBBB><TR><TD>';
cal += '<TABLE BORDER=0 CELLSPACING=0 CELLPADDING=1>' + TR_start;
cal += '<TD COLSPAN="' + DAYS_OF_WEEK + '" BGCOLOR="#EFEFEF"><CENTER><B>';
cal += month_of_year[month] + ' ' + year + '</B>' + TD_end + TR_end;
cal += TR_start;
// LOOPS FOR EACH DAY OF WEEK
for(index=0; index < DAYS_OF_WEEK; index++)
{
// BOLD TODAY'S DAY OF WEEK
if(weekday == index)
cal += TD_start + '<B>' + day_of_week[index] + '</B>' + TD_end;
// PRINTS DAY
else
cal += TD_start + day_of_week[index] + TD_end;
}
cal += TD_end + TR_end;
cal += TR_start;
// FILL IN BLANK GAPS UNTIL TODAY'S DAY
for(index=0; index < Calendar.getDay(); index++)
cal += TD_start + '' + TD_end;
// LOOPS FOR EACH DAY IN CALENDAR
for(index=0; index < DAYS_OF_MONTH; index++)
{
if( Calendar.getDate() > index )
{
// RETURNS THE NEXT DAY TO PRINT
week_day =Calendar.getDay();
// START NEW ROW FOR FIRST DAY OF WEEK
if(week_day == 0)
cal += TR_start;
if(week_day != DAYS_OF_WEEK)
{
// SET VARIABLE INSIDE LOOP FOR INCREMENTING PURPOSES
var day = Calendar.getDate();
// HIGHLIGHT TODAY'S DATE
if( today==Calendar.getDate() )
cal += highlight_start + day + highlight_end + TD_end;
// PRINTS DAY
else
cal += TD_start + day + TD_end;
}
// END ROW FOR LAST DAY OF WEEK
if(week_day == DAYS_OF_WEEK)
cal += TR_end;
}
// INCREMENTS UNTIL END OF THE MONTH
Calendar.setDate(Calendar.getDate()+1);
}// end for loop
cal += '</TD></TR></TABLE></TABLE>';
// PRINT CALENDAR
document.write(cal);
// End -->
</script>
Add an align=right to the table definition on line 38.
So you'll have:
cal = '<TABLE ALIGN=RIGHT BORDER=1 CELLSPACING=0 CELLPADDING=0 BORDERCOLOR=BBBBBB><TR><TD>';
Instead of:
cal = '<TABLE BORDER=1 CELLSPACING=0 CELLPADDING=0 BORDERCOLOR=BBBBBB><TR><TD>';

Categories

Resources