undefined innerHTML (when trying to refresh) - button

hi everybody I'm trying to make a Random Generator of Discourses but I don't want to refresh the entire page in order to get a new string, so I thought that maybe innerHTML could be my solution. Unfortunately It gives me an "UNDEFINED" result when I click on the button. I don't know how to proceed. Thanks in advance.
<span id="generator" style="font-size: 20px; font-weight: bold;">
<script language="javascript" type="text/javascript">
Words1 = new Array("blablabla1","blablabla2")
Words2 = new Array("blablabla3","blablabla4")
var random = document.write('- ' +
Words1[Math.floor((Math.random() * 100000) % Words1.length)] +
' ' +
Words2[Math.floor((Math.random() * 100000) % Words2.length)] +
'.\n' );
function refresh(){
document.getElementById('generator').innerHTML = random;
}
</script>
</span>
<input type='button' onclick='refresh()' value='refresh'/>

You are wrapping the javascript code with the span tag. Should be like this and put the code inside de function:
<span id="generator" style="font-size: 20px; font-weight: bold;"></span>
<script language="javascript" type="text/javascript">
function refresh(){
Words1 = new Array("blablabla1","blablabla2")
Words2 = new Array("blablabla3","blablabla4")
var random = document.write('- ' +
Words1[Math.floor((Math.random() * 100000) % Words1.length)] +' ' + Words2[Math.floor((Math.random() * 100000) % Words2.length)] +'.\n' );
document.getElementById('generator').innerHTML = random;
}
</script>
<input type='button' onclick='refresh()' value='refresh'/>

Related

Embed specific range from Google Sheets in website so that it is editable by website users

I want to embed a specific range of cells from a Google Docs spreadsheet (or if that doesn't work the whole sheet without header and toolbar) in a website, so that any website visitor can input their data.
I know how to embed a specific range of cells an html table, but that doesn't allow website users to edit the sheet.
A similar question was asked several years ago here but the suggested solution doesn't seem to work anymore.
I called this the htmlSpreadsheet you can use as a dialog or deploy as webapp the doGet is already to go. It's still a pretty simple app. There's a lot of room for customization.
Here's the code.gs file:
function onOpen()
{
SpreadsheetApp.getUi().createMenu('HTML Spreadsheet')
.addItem('Run Spreadsheet in Dialog', 'htmlSpreadsheet')
.addToUi();
}
var SSID='SpreadSheetID';
var sheetName='Sheet1';
function htmlSpreadsheet(mode)
{
var mode=(typeof(mode)!='undefined')?mode:'dialog';
var br='<br />';
var s='';
var hdrRows=1;
var ss=SpreadsheetApp.openById(SSID);
var sht=ss.getSheetByName(sheetName);
var rng=sht.getDataRange();
var rngA=rng.getValues();
s+='<table>';
for(var i=0;i<rngA.length;i++)
{
s+='<tr>';
for(var j=0;j<rngA[i].length;j++)
{
if(i<hdrRows)
{
s+='<th id="cell' + i + j + '">' + '<input id="txt' + i + j + '" type="text" value="' + rngA[i][j] + '" size="10" onChange="updateSS(' + i + ',' + j + ');" />' + '</th>';
}
else
{
s+='<td id="cell' + i + j + '">' + '<input id="txt' + i + j + '" type="text" value="' + rngA[i][j] + '" size="10" onChange="updateSS(' + i + ',' + j + ');" />' + '</th>';
}
}
s+='</tr>';
}
s+='</table>';
//s+='<div id="success"></div>';
s+='</body></html>';
switch (mode)
{
case 'dialog':
var userInterface=HtmlService.createHtmlOutputFromFile('htmlss').setWidth(1000).setHeight(450);
userInterface.append(s);
SpreadsheetApp.getUi().showModelessDialog(userInterface, 'Spreadsheet Data for ' + ss.getName() + ' Sheet: ' + sht.getName());
break;
case 'web':
var userInterface=HtmlService.createHtmlOutputFromFile('htmlss').setWidth(1000).setHeight(450);
return userInterface.append(s).setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
}
function updateSpreadsheet(i,j,value)
{
var ss=SpreadsheetApp.openById(SSID);
var sht=ss.getSheetByName(sheetName);
var rng=sht.getDataRange();
var rngA=rng.getValues();
rngA[i][j]=value;
rng.setValues(rngA);
var data = {'message':'Cell[' + Number(i + 1) + '][' + Number(j + 1) + '] Has been updated', 'ridx': i, 'cidx': j};
return data;
}
function doGet()
{
var output=htmlSpreadsheet('web');
return output;
}
This is the htmlss.html file:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function() {
});
function updateSS(i,j)
{
var str='#txt' + String(i) + String(j);
var value=$(str).val();
$(str).css('background-color','#ffff00');
google.script.run
.withSuccessHandler(successHandler)
.updateSpreadsheet(i,j,value)
}
function successHandler(data)
{
$('#success').text(data.message);
$('#txt' + data.ridx + data.cidx).css('background-color','#ffffff');
}
console.log('My Code');
</script>
<style>
th{text-align:left}
</style>
</head>
<body>
<div id="success"></div>
Following post will be helpfull:
https://support.google.com/docs/answer/37579?hl=fr&ref_topic=2818998
And with some added value, the following is the template you may want to try, where ------ is specific code to your sheet
<iframe style="border: 0;" src="https://docs.google.com/spreadsheets/-----/pubhtml?gid=--------&range=C2:E&chrome=false&single=true&widget=false&headers=false" width="800" height="750" frameborder="0" scrolling="yes"><span data-mce-type="bookmark" style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" class="mce_SELRES_start"></span><span data-mce-type="bookmark" style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" class="mce_SELRES_start"></span><span data-mce-type="bookmark" style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" class="mce_SELRES_start"></span></iframe>

How to add numbered section folding to rmarkdown

I am trying to show sections of text only after clicking on them (very much like code folding).
So far I am using the following html script at the beginning of my Rmd file:
<script language="javascript">
function toggle(num) {
var ele = document.getElementById("toggleText" + num);
var text = document.getElementById("displayText" + num);
if(ele.style.display == "block") {
ele.style.display = "none";
text.innerHTML = "show";
}
else {
ele.style.display = "block";
text.innerHTML = "hide";
}
}
</script>
But whenever I use it for sections/headers I lose the automatic numbering.
<a id="displayText" href="javascript:toggle(5);"><h1>I would like to code fold this section
</h1></a>
<div id="toggleText5" style="display: none">
Bla bla
</div>
And get a heading with numbering like this:
1 - I would like to code fold this section

Star rating using MVC5

How to implement star rating using Mvc5?
I found a code in this link http://www.dotnetfunda.com/articles/show/2828/developing-a-star-rating-in-aspnet-mvc and I did database and I added a Controller and two partial view.
here is the partial view that gave me the problem.
#model string
#{
Single m_Average = 0;
Single m_totalNumberOfVotes = 0;
Single m_totalVoteCount = 0;
Single m_currentVotesCount = 0;
Single m_inPercent = 0;
var thisVote = string.Empty;
if (Model.Length > 0)
{
// calculate total votes now
string[] votes = Model.Split(',');
for (int i = 0; i < votes.Length; i++)
{
m_currentVotesCount = Int16.Parse(votes[i]);
m_totalNumberOfVotes = m_totalNumberOfVotes + m_currentVotesCount;
m_totalVoteCount = m_totalVoteCount + (m_currentVotesCount * (i + 1));
}
m_Average = m_totalVoteCount / m_totalNumberOfVotes;
m_inPercent = (m_Average * 100) / 5;
thisVote = "<span style=\"display: block; width: 65px; height: 13px; background: url(/images/starRating.png) 0 0;\">" +
"<span style=\"display: block; width: " + m_inPercent + "%; height: 13px; background: url(/images/starRating.png) 0 -13px;\"></span> " +
"</span>" +
"<span class=\"smallText\">Overall ratings: <span itemprop=\"ratingCount\">" + m_totalNumberOfVotes + "</span> | Rating: <span itemprop=\"ratingValue\">" + m_Average.ToString("##.##") + "</span> out of 5 </span> ";
}
}
<div itemprop="aggregateRating" itemscope itemtype="http://schema.org/AggregateRating">
<meta itemprop="bestRating" content="5" />
<meta itemprop="worstRating" content="1">
<meta itemprop="ratingValue" content="#m_Average.ToString("##.##") %>" />
#Html.Raw(thisVote)
</div>
when I run my application I get this error: INPUT STRING IS NOT IN A CORRECT FORMAT...
The name says it all "INPUT STRING IS NOT IN THE CORRECT FORMAT". Where you you have input strings? on the Parse() methods.
Check the contents of your vote[] array. I am pretty sure one of those values is cannot be parsed numerically.

Change color every other row with $.each

I am making a golf leaderboard and want to change the color on every other row to be slightly grey... How do I do that?
Here is how I get the leaderboard using ajax:
$.get("http://mypage.com/json/getleaderboard.php", function(data) {
var output = '';
output += '<li class="leaderboard-head"><span class="leaderboard-head-placement"> </span><span class="leaderboard-name tr" key="name">Name</span><span class="leaderboard-head-points">P</span></li>';
$.each(data, function (i, val) {
output += '<li><span class="leaderboard-placement">' + val.placement + '</span><span class="leaderboard-name">' + val.name + '</span><span class="leaderboard-points">' + val.points + '</span></li>';
});
$('#leaderboardList').append(output).listview('refresh');
}, "json");
hoping for help and thanks in advance :-)
You can use the nth-child selector. e.g.
<ul class="leaderboard">
<li class="leaderboard-head">1</li>
<li class="leaderboard-head">2</li>
<li class="leaderboard-head">3</li>
<li class="leaderboard-head">4</li>
<li class="leaderboard-head">5</li>
<li class="leaderboard-head">6</li>
</ul>
CSS
.leaderboard-head:nth-child(odd){ // Odd/Even according to your requirements
background-color: gray;
}
Note that this will only work in CSS3 compatible browsers. For others you can use :
$(".leaderboard").children(":nth-child(odd)").each(function(){ // Odd/Even according to your requirements
$(this).css("background", "gray");
});
FIDDLE
You can remove the css/jquery and it will still work.
Simple, you use CSS and do (assuming there is a class leaderboard-entry):
li.leaderboard-entry {
background-color: #efefef;
}
li.leaderboard-entry:nth-child(even) {
background-color: #afafaf;
}
No JavaScript required.
On a more general note, your code should read
$.get("http://mypage.com/json/getleaderboard.php")
.done(function(data) {
$('<li class="leaderboard-head">' +
'<span class="leaderboard-head-placement"> </span>' +
'<span class="leaderboard-name tr" key="name">Name</span>' +
'<span class="leaderboard-head-points">P</span>' +
'</li>'
).appendTo('#leaderboardList');
$.each(data, function (i, val) {
$('<li class="leaderboard-entry">')
.append($('<span class="leaderboard-placement">', {text: val.placement}))
.append($('<span class="leaderboard-name">', {text: val.name}))
.append($('<span class="leaderboard-points">', {text: val.points}))
.appendTo('#leaderboardList');
});
$('#leaderboardList').listview('refresh');
});
Don't create HTML by concatenating arbitrary strings. This is the single source of cross site scripting vulnerabilities (and blown markup).
Also, declaring the request type ("json") in jQuery is superfluous if the server sends JSON and sets the correct Content-Type header.
if you sway to do using jquery rather than css (good one)
$.get("http://mypage.com/json/getleaderboard.php", function(data) {
var output = '';
output += '<li class="leaderboard-head"><span class="leaderboard-head-placement"> </span><span class="leaderboard-name tr" key="name">Name</span><span class="leaderboard-head-points">P</span></li>';
$.each(data, function (i, val) {
var color_style_class = 'blue';
if (i % 2 == 0)
{
color_style_class = 'green';
}
else
{
color_style_class = 'red';
}
output += '<li><span class="leaderboard-placement ' + color_style_class + '">' + val.placement + '</span><span class="leaderboard-name">' + val.name + '</span><span class="leaderboard-points">' + val.points + '</span></li>';
});
$('#leaderboardList').append(output).listview('refresh');
}, "json");
define new style for 'blue' , 'green' and 'red' or whatever you like

Including <script> elements in a custom infowindow

I am using the Google Maps API to create a custom InfoWindow that contains fusion table content. I also want to embed content from an external site in the InfoWindow, but cannot get the code to work. The embed code from the external site is:
<link type="text/css" rel="stylesheet" media="all" href="http://www.foodsecurityportal.org/sites/all/modules/tic_countries/tic_countries_widget.css" />
<div class="web-widgets-inline" id="web_widgets_inline_country_news_36">
<script src="http://www.foodsecurityportal.org/country/widget/36"></script>
</div>
I am trying to embed it into my InfoWindow as follows, with the external URL and ID referenced in my fusion table. My problem is that I cannot get the inline </script> element to function. Including it in full as </script> prevents the map from loading at all, whilst trying to break it up (e.g "<"+"/script>" (as in the below snippet) prevents the embedded script from running.
Any ideas? Please give a full explanation if possible as I'm a novice. Many thanks.
function initialize() {
map = new google.maps.Map(document.getElementById('map_canvas'), {
center: new google.maps.LatLng(10, 30),
zoom: 2,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
layer = new google.maps.FusionTablesLayer(tableid);
layer.setQuery("SELECT 'Country Geometry' FROM " + tableid);
layer.setMap(map);
layer2 = new google.maps.FusionTablesLayer(tableid2);
layer2.setQuery("SELECT 'Site Location' FROM " + tableid2);
layer2.setMap(map);
google.maps.event.addListener(layer, 'click', function(e) {
e.infoWindowHtml = "<div class='googft-info-window' style='font-family: sans-serif; width: 500px; height: 300px; overflow: auto;'>"
e.infoWindowHtml += "<b>" + e.row['Site Name'].value + "</b><br />"
e.infoWindowHtml += "<img src=" + e.row['Image URL'].value + "><br />"
e.infoWindowHtml += "<link type=text/css rel=stylesheet media=all href=http://www.foodsecurityportal.org/sites/all/modules/tic_countries/tic_countries_widget.css />"
e.infoWindowHtml += "<div class=" + e.row['IFPRI Ref1'].value + " style='width: 95%; height: 150px; overflow: auto;'>"
e.infoWindowHtml += "<script src=" + e.row['IFPRI Ref2'].value + "type='text/javascript'><"+"/script>"
e.infoWindowHtml += "</div></div>"
});
There is a space missing before the type-attribute, the src is broken.
But the space wouldn't solve the problem.
I guess the API is using innerHTML to set the content. Therefore the script-element could be injected into the infowindow, but it doesn't execute.
You need to use a DOM-method to inject the script and execute it, e.g. appendChild() .
Fixed click-handler:
//add a click listener to the layer
google.maps.event.addListener(layer, 'click', function(e) {
e.infoWindowHtml = "<div id='someID' class='googft-info-window' style='font-family: sans-serif; width: 500px; height: 300px; overflow: auto;'>\
<b>" + e.row['Site Name'].value + "</b><br />\
<img src=" + e.row['Image URL'].value + "><br />\
<link type=text/css rel=stylesheet media=all href=http://www.foodsecurityportal.org/sites/all/modules/tic_countries/tic_countries_widget.css />\
<div class=" + e.row['IFPRI Ref1'].value + " style='width: 95%; height: 150px; overflow: auto;'>\
</div></div>";
//append the script to the body, it doesn't matter where you place it
var script=document.createElement('script');
script.setAttribute('src',e.row['IFPRI Ref2'].value);
document.getElementsByTagName('body')[0].appendChild(script);
});
looks like you are missing "'s in this line:
e.infoWindowHtml += "<link type=text/css rel=stylesheet media=all href=http://www.foodsecurityportal.org/sites/all/modules/tic_countries/tic_countries_widget.css />"
should be something like:
e.infoWindowHtml += "<link type='text/css' rel=stylesheet media='all' href='http://www.foodsecurityportal.org/sites/all/modules/tic_countries/tic_countries_widget.css' />"
Update:
You are saying this:
e.infoWindowHtml += "<script src=" + e.row['IFPRI Ref2'].value + "type='text/javascript'><"+"/script>"
isn't working. Why do you need to include it when the infoWindow opens? Why not just include it as part of the page (statically loaded)? Is the src different for each infoWindow?
Update2:
Not all of the markers/polygons have a value in the row "IFPRI Ref2". It works if I click on Bangladesh on this version of your map

Resources