How to reach JS variables in HTML table - javascript

I have a Javascript and html like below. All I want is to change the values bold areas with the "currMonth" and "currYear" variables' values, to make them dynamic. I appreciate for your help!.
<script type="text/javascript">
$(document).ready(function () {
var date = new Date();
var currMonth = date.getMonth();
var currYear= date.getFullYear();
currMonth +=1;
});
</script>
<html>
...
<table>
<td>...<td>
...
<td align="right" class="arrowIcon">
<img src="images/rightarrow.gif" border="0">
</td>
</table>
...
</html>
Thanks.
Edit: Thanks for the answers guys. All of them working!

You can update href in JavaScript:
$(document).ready(function () {
var date = new Date();
var currMonth = date.getMonth();
var currYear= date.getFullYear();
currMonth +=1;
$('table .arrowIcon>a').each(function(i, el) {
$(el).attr('href', 'index.php?m='+currMonth+'&y='+currYear+'&cat=0')
}
});

In plain javascript, use getElementById() to fetch the anchor node, and setAttribute() to change the link. Example given here. But as you are using jQuery, it's easier to use the .attr() function. Eg:
$('a').attr('href', 'index.php?m=' + currentMonth + '...');

you can get the href of the link and replace the ** ** placeholders with your variables like this:
var href= $('.arrowIcon).find('a').attr('href');
href = href.replace("**8**", currMonth);
href = href.replace("**2015**", currYear);
$('.arrowIcon').find('a').attr('href', href);
so, the other option to make it truly dynamic I would solve like this:
link html:
<img src="images/rightarrow.gif" border="0">
js:
$(document).ready(function () {
var date = new Date();
var currMonth = date.getMonth();
var currYear= date.getFullYear();
currMonth +=1;
var cat= $('.arrowIcon).find('a').data('cat');
$('.arrowIcon')
.find('a')
.attr('href',"index.php?m="+currMonth+"&y="+currYear+"&cat="+cat);
});

Here is a example that do not require jQuery if this is the only thing you are doing with javascript.
First of i moved the script tag to the buttom of the document to make sure that the html structure is created before the javascript is run. This is in general a good idea to not halt the rendering with javascript before the whole document is loaded, so placing the script tags in the bottom is best.
<html>
...
<table>
<td>...<td>
...
<td align="right" class="arrowIcon">
<img src="images/rightarrow.gif" border="0">
</td>
</table>
...
<script type="text/javascript">
var date = new Date();
var currMonth = date.getMonth();
var currYear= date.getFullYear();
currMonth +=1;
var atag = document.querySelector("table td a");
atag.href = 'index.php?m='+currMonth+'&y='+currYear+'&cat=0';
</script>
</html>

Related

how to get Id inside table tag

I have html and script like this :
<!DOCTYPE html>
<html>
<body>
<table>
<tr>
<th id="vehicleNo">Vehicle No.</th>
<td><input type="text" name="vehicleNo"/></td>
</tr>
</table>
<p>When you leave the input field, a function is triggered which transforms the input text to upper case.</p>
<script>
document.getElementById("vehicleNo").onchange = function() {myFunction3()};
var time1;
var time2;
var text1 = "greater than 30 sec";
var text2 = "less than 30 sec";
function myFunction3() {
var d2 = new Date();
var y = document.getElementById("vehicleNo");
y= d2.getTime();
time2 = y;
var checkTime2 = d2.toLocaleTimeString();
console.log(this.time2);
console.log(this.checkTime2);
//console.log(time2);
}
</script>
</body>
why the value not showing on console? am I wrong in accessing the id in the table tag? how to access id inside table tag? many thanks
To run the code you need the change the following things:
Bind the change handler with input field rather than the table cell
Bind the change handler on load of page so that whenever user make change in control value the event can trigger
For your reference :
<html>
<head>
<script>
function myfunction(){
document.getElementById("vehicleNo").onchange = function() {myFunction3()};
}
var time1;
var time2;
var text1 = "greater than 30 sec";
var text2 = "less than 30 sec";
function myFunction3() {
var d2 = new Date();
var y = document.getElementById("vehicleNo");
y= d2.getTime();
time2 = y;
var checkTime2 = d2.toLocaleTimeString();
console.log(this.time2);
console.log(checkTime2);
//console.log(time2);
}
</script>
</head>
<body onload ="myfunction()">
<table>
<tr>
<th>Vehicle No.</th>
<td><input type="text" id="vehicleNo" name="vehicleNo"/></td>
</tr>
</table>
<p>When you leave the input field, a function is triggered which transforms the input text to upper case.</p>
</body>
</html>

How to use an element property to pass a variable from Javascript

I'm attempting to send emails using an HTML template.
I've looked at this post:
(https://stackoverflow.com/questions/33178702/passing-variables-into-html-code)
Would either of the two code examples be close to something that could work to pass the variables from the Javascript to the HTML template?
My javascript variables are named detail2, detail3, detail4, detail5 and detail6.
1st attempt:
<html>
<head>
<script>
{
var detail2 = document.getElementById("detail2").innerHTML;
var detail3 = document.getElementById("detail3").innerHTML;
var detail4 = document.getElementById("detail4").innerHTML;
var detail5 = document.getElementById("detail5").innerHTML;
var detail6 = document.getElementById("detail6").innerHTML;
}
}
</script>
</head>
<body>
<p>
<br>"Punctual? " document.getElementById('detail2').value<br>
<br>"Attention to detail? " document.getElementById('detail3').value<br>
<br>"Overall Professionalism? " document.getElementById('detail4').value<br>
<br>"Date of Service: " document.getElementById('detail5').value<br>
<br>"Notes/Details: " document.getElementById('detail6').value<br>
</p>
</body>
</html>
2nd attempt:
<html>
<head>
<script>
{
<input type="hidden" id="Detail2" value="detail2" />
<input type="hidden" id="Detail3" value="detail3" />
<input type="hidden" id="Detail4" value="detail4" />
<input type="hidden" id="Detail5" value="detail5" />
<input type="hidden" id="Detail6" value="detail6" />
}
}
</script>
</head>
<body>
<p>
<br>"Punctual? " document.getElementById('detail2').value<br>
<br>"Attention to detail? " document.getElementById('detail3').value<br>
<br>"Overall Professionalism? " document.getElementById('detail4').value<br>
<br>"Date of Service: " document.getElementById('detail5').value<br>
<br>"Notes/Details: " document.getElementById('detail6').value<br>
</p>
</body>
</html>
Finally, the method given on GAS Dev is below, but this only confuses me more. I am sure I've been at this too long and I'm burned out, I just can't seem to see the answer on this one.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<table>
<? for (var i = 0; i < data.length; i++) { ?>
<tr>
<? for (var j = 0; j < data[i].length; j++) { ?>
<td><?= data[i][j] ?></td>
<? } ?>
</tr>
<? } ?>
</table>
</body>
</html>
If anyone can help it's much appreciated!
Below is the Javascript from the .gs script file.
function SendEmail() {
// initialize data
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var range = sheet.getDataRange();
var values = range.getValues();
// iteration loop
for (var i = 1; i<values.length; i++) {
// current times for comparator
var month = new Date().getMonth(); // returns today as 0-11 -- Jan is 0
var day = new Date().getDate(); // returns today as 1-31
var hour = new Date().getHours(); // returns today as 0-23
var minute = new Date().getMinutes(); // returns today as 0-59
// pull data from spreadsheet rows
var company = values[i][0];
var rating = values[i][1];
var detail1 = values[i][2];
var detail2 = values[i][3];
var detail3 = values[i][4];
var detail4 = values[i][5];
var detail5 = values[i][6];
var sendTime = values[i][7];
// character send times for comparator
var cSendMonth = sendTime.getMonth(); // returns sendMonth as 0-11 -- Jan is 0
var cSendDay = sendTime.getDate(); // returns sendDay as 1-31
var cSendHour = sendTime.getHours(); // returns sendHour as 0-23
var cSendMinute = sendTime.getMinutes(); // returns sendMinute as 0-59
// comparator
if(cSendMonth == month) {
if(cSendDay == day) {
if(cSendHour == hour) {
if(cSendMinute == minute) {
var htmlBody = HtmlService.createHtmlOutputFromFile('mail_template').getContent();
MailApp.sendEmail({
to: Session.getActiveUser().getEmail(),
subject: 'Test Email markup2 - ' + new Date(),
htmlBody: htmlBody,
});
} // end if minute test
}// end if hour test
}// end if day test
}// end if month test
}// end for loop
}
Can you try:
<html>
<head>
<script>
(function() {
var detail2 = document.getElementById("detail2").innerHTML;
document.getElementById("detail2_val").innerHTML = detail2;
})();
</script>
</head>
<body>
<p>
<br>"Punctual?" <span id="detail2_val"></span><br>
</p>
</body>
</html>
Currently, this line:
var htmlBody = HtmlService.createHtmlOutputFromFile('mail_template').getContent();
will not evaluate a template.
The method being used is:
createHtmlOutputFromFile('mail_template')
HtmlService has quite a few methods for creating html content. You need to use:
HtmlService.createTemplateFromFile(filename).evaluate()
There are some possible things that could go wrong in your overall work flow. If the situation is one in which you are writing data, and then immediately trying to read that same data that was just written, there could be a problem with the new data not being available to be read in such a short time span.
I would use:
SpreadsheetApp.flush();
immediately after writing the new data, and before creating the template.
Only your third html example has code for a template. To retrieve data and put it into a template, a scriptlet must either run a function, that then retrieves the data, or the data must be in global variables. The situation with global variable makes no sense, because you are using dynamic data, so a function would need to run to first put the data into a global variable. The function might as well just return the data directly. So, your scriptlet will probably need to run a server side function and return text or HTML to the html template. You probably need to use a printing scriptlet.
Apps Script documentation - force printing scriptlets

Can't get JavaScript output on website

The website is supposed to display a message counting down to the tax day. I can't seem to get anything to display on the page. The scrollbar doesn't even show up with the color even though I put in the write code. Some advice please.
<!DOCTYPE HTML>
<html>
<head><meta charset="utf-8">
<title>TaxDay</title>
<script type="text/javascript">
<!-- Hide from old browsers
function scrollColor() {
styleObject=document.getElementsByTagName('html')[0].style
styleObject.scrollbarFaceColor="#857040"
styleObject.scrollbarTrackColor="#f4efe9"
}
function countDown() {
var today = new Date()
var day of week = today.toLocaleString()
dayLocate = dayofweek.indexOf(" ")
weekDay = dayofweek.substring(0, dayLocate)
newDay = dayofweek.substring(dayLocate)
dateLocate = newday.indexOf(",")
monthDate = newDay.substring(0, dateLocate+1)}
yearLocate = dayofweek.indexOf("2016")
year = dayofweek.substr(yearLocate, 4)
var taxDate = new Date ("April 16, 2017")
var daysToGo = taxDate.getTime()-today.getTime()
var daysToTaxDate = Math.ceil(daysToGo/(1000*60*60*24))
function taxmessage() {
var lastModDate = document.lastModified
var lastModDate = lastModDate.substring(0,10)
taxDay.innerHTML = "<p style='font-size:12pt; font-
family:helvetica;'>Today is "+weekDay+" "+monthDate+" "+year+".
You have "+daysToTaxDate+" days to file your taxes.</p>"
}
}
//-->
</script>
The <div> id is taxDay if it's relevant. The body onLoad event handlers are scrollColor(); countDown(); and taxmessage().
you are not closing the countdown() function before the taxmessage() function - meaning that taxmessage is nested within countdown(). Also you do not have semicolons ";" after each line of the js. You should rewrite the code to either include the function of taxmessage() or close out countdown() first and call taxmessage with arguments passed to get the date variables.
check your console for errors

DateTime not working in angular.js

I've got this line of code
<h3> <script>Date.now</script>{{$flow.files[0].name}} </h3>
Basically All i'm wanting to do is put the date infront of the filename thats generated from the {{}}.
It currently shows nothing, The unix timestamp might be better but i can only get it to show text that i type infront.
I have tried {{Date.now(); $flow.files[0].name}} Which hasn't worked.
If you want to do it with JavaScript like your first attempt, you should have something like this:
<div ng-app="app">
<span id="dateHere"></span> - {{fileName}}
<script>
document.getElementById("dateHere").innerHTML = Date();
</script>
</div>
and if you want to have more control on your date format:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js"></script>
<div ng-app='app' ng-controller='Ctrl'>
<span id="dateHere"></span> - {{fileName}}
<script>
document.getElementById("dateHere").innerHTML = Date();
var date = new Date();
var currentYear = date.getFullYear();
var currentMonth = date.getMonth();
var currentDate = date.getDate();
var customDate = currentMonth + '-' + currentDate + '-' + currentYear;
document.getElementById("dateHere").innerHTML = customDate;
</script>
</div>
<script>
angular.module('app', []).controller('Ctrl', function($scope){
$scope.fileName = 'your file name';
})
</script>
-> on Plunker
Try something like this:
Controller:
$scope.myDate = new Date();
HTML:
{{myDate | date: 'MMM d, y h:mm:ss a' }} {{$flow.files[0].name}}
I used the filter date to format the date.

Pull value from table

Hello I have the following on a page and I would like to pull the value: 36424. the value will change thus Im trying to create a function that will pull it when i call on the function.
<table cellspacing="0" cellpadding="3" rules="cols" border="1"
id="OSDataCount" style="color:Black;background-color:White;border-
color:#999999;border-width:1px;border-style:Solid;border-collapse:collapse;">
<tr style="color:White;background-color:Black;font-weight:bold;">
<th scope="col">COUNT(*)</th>
</tr><tr>
<td>36424</td>
</tr>
</table>
cheers
No need for jQuery:
var table = document.getElementById('OSDataCount');
alert(table.rows[1].children[0].innerHTML); // -> 36424
See example →
Using jQuery:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript"></script>
<script type='text/javascript'>
function alertval() {
var htmlval = $('#OSDataCount tr:eq(1)>td:first').html();
var textval = $('#OSDataCount tr:eq(1)>td:first').text();
alert("Val:" + val);
}
</script>
See http://api.jquery.com/text/, http://api.jquery.com/html/
Using raw JavaScript:
function alertval() {
var el = document.getElementById("OSDataCount");
alert("Val:" + el.rows[1].cells[0].innerHTML);
}
Adding a little detail to previous (correct) answers:
<script type="text/javascript">
window.onload = function() {
var table = document.getElementById('OSDataCount');
var number = table.rows[1].cells[0].innerHTML;
alert (number);
}
</script>
var value = document.evaluate('id(OSDataCount)/tr/td', document, null, XPathResult.NUMBER_TYPE);
going off a quick search/reach. Probably won't work, but worth a try.

Categories

Resources