Javascript creates my html template tables. The function code below is called inside a for loop for TABLE which is inside a for loop for ROUND. The two loops are determined by variables (NumberOf)tables and (NumberOf)rounds, so they vary with use. The database needs to maintain records of the 6 fields for each TABLE in each ROUND, but those field names have not been programmed (yet?) to vary from one ROUND/TABLE instance to another for multiple reasons: it's not clear how to do so in a way to jeehaw with the python data models; I hope there is an easier alternative and; I want to not overburden the server with jinja-type code in the javascript as has been mentioned elsewhere on stackoverflow, for example.
function round1(ROUND,TABLE){
var tt;
tt = ' <div class="table">Table '+ TABLE +''
tt += ' <div class="flex-container partners1">'
tt += ' partners1'
tt += ' <input type="text" maxlength="8" name="partner1" value="name' + Number(1+4*(TABLE-1)) + '"></input>'
tt += ' <input type="text" maxlength="8" name="partner2" value="name' + Number(2+4*(TABLE-1)) + '"></input>'
tt += ' <input type="number" name="score1" >score1</input> '
tt += ' </div>'
tt += ' <p>'
tt += ''
tt += ' </p>'
tt += ' <div class="flex-container partners2">'
tt += ' partners2'
tt += ' <input type="text" maxlength="8" name="partner3" value="name' + Number(3+4*(TABLE-1)) + '"></input>'
tt += ' <input type="text" maxlength="8" name="partner4" value="name' + Number(4+4*(TABLE-1)) + '"></input>'
tt += ' <input type="number" name="score2" >score2</input> '
tt += ' </div>'
tt += ' </div>'
return tt;
}
The data models are given below. I am concerned with the processing burden of Posting data back to the server and Getting the results back to the template. But I am also troubled with how to parse and process the data items efficiently.
class Parties(ndb.Model):
email = ndb.StringProperty()
page = ndb.KeyProperty(kind=Pages)
name = ndb.StringProperty()
tables = ndb.IntegerProperty(default=0)
rounds = ndb.IntegerProperty(default=0)
class Rounds(ndb.Model):
party = ndb.KeyProperty(kind=Pages)
number = ndb.IntegerProperty(default=0)
class Tables(ndb.Model):
party = ndb.KeyProperty(kind=Pages)
number = ndb.IntegerProperty(default=0)
partner1 = ndb.StringProperty(default="")
partner2 = ndb.StringProperty(default="")
partner3 = ndb.StringProperty(default="")
partner4 = ndb.StringProperty(default="")
score1 = ndb.IntegerProperty(default=0)
score2 = ndb.IntegerProperty(default=0)
So I am looking for ideas on how I can rewrite the javascript, or redesign the database, and how to construct the python get and post template_values to coordinate the two.
Upon further analysis, I will attempt to rewrite my Python code to do much of the processing that is done now with javascript, hoping that the mismatch of data and code can be minimized. I was hoping to get ideas of ways to avoid such a rewrite by asking this question.
Or to minimize Python recoding because there is much javascript code not shown that would also have to be redone, I may revise the javascript code so that each input name includes its round and table values: for example, instead of name="parent1", name="r0t0parent1" for parent1 in round 1 and table 1. Python code should be able to parse self.request.get's of such names and hopefully the jinja2 template responses will not be too burdensome to create and parse, but I do not look forward to developing the additional jinja2. Perhaps the ideas suggested here can be employed. I welcome any further advice.
Related
I'm trying to finish my final project for my introductory web development course (I'm very new to javascript and html), which is a simple Mad Libs project. I've been running into problems all day with trying to get it to work, and I think I've largely eradicated most of the bugs. I've really hit a roadblock though, with the button I'm using that is supposed to load in the results and call the function that builds the story using an event listener in the javascript file. When I run my program, the button doesn't do a thing. I checked the Google Chrome developer console, and I'm not getting any error messages or anything, so I have no clue what I'm doing wrong.
Here's my javascript file (named mad_libs_1.js):
var story = document.querySelector("#story");
var adjective1 = document.querySelector("#adjective1");
var verbEndingInED = document.querySelector("#verbEndingInED");
var nounPlural1 = document.querySelector("#nounPlural1");
var liquid = document.querySelector("#liquid");
var nounPlural2 = document.querySelector("#nounPlural2");
var famousPerson = document.querySelector("#famousPerson");
var place = document.querySelector("#place");
var occupation = document.querySelector("#occupation");
var noun1 = document.querySelector("#noun1");
var nationality = document.querySelector("#nationality");
var femaleCelebrity = document.querySelector("#femaleCelebrity");
var noun2 = document.querySelector("#noun2");
var femaleFriend = document.querySelector("#femaleFriend");
var nounPlural3 = document.querySelector("#nounPlural3");
var number = document.querySelector("#number");
var adjective2 = document.querySelector("#adjective2");
//event listener for the button
var finished = document.querySelector("#finished");
if(finished){
finished.addEventListener("click", createStory, false);
}
function createStory(){
console.log("createStory HAS BEEN CALLED");
var finalStory = "";
finalStory += "I enjoy long, " + adjective1.bold();
finalStory += " walks on the beach, getting " + verbEndingInED.bold();
finalStory += " in the rain and serendipitous encounters with " + nounPlural1.bold();
finalStory += ". I really like piña coladas mixed with " + liquid.bold();
finalStory += ", and romantic, candle-lit " + nounPlural2.bold();
finalStory += ". I am well-read from Dr. Seuss to " + famousPerson.bold();
finalStory += ". I travel frequently, especially to " + place.bold();
finalStory += ", when I am not busy with work. (I am a " + occupation.bold();
finalStory += ".) I am looking for " + noun.bold();
finalStory += " and beauty in the form of a " + nationality.bold();
finalStory += " goddess. She should have the physique of " + femaleCelebrity.bold();
finalStory += " and the " + noun2.bold();
finalStory += " of " + femaleFriend.bold();
finalStory += ". I would prefer if she knew how to cook, clean, and wash my " + nounPlural3.bold();
finalStory += ". I know I’m not very attractive in my picture, but it was taken " + number.bold();
finalStory += " days ago, and I have since become more " + adjective2.bold() + ".";
story.innerHTML = finalStory;
console.log(story + " IS THE STORY");
}
and here's my html:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8" />
<title>Mad Libs 1</title>
<script type="text/javascript" src="mad_libs_1.js"></script>
</head>
<body lang="en-US">
<div class="container-fluid">
<h1>Mad Libs 1</h1>
</div>
<div class="container-fluid">
<ul>
<li>Adjective: <input type="text" name="adjective1" id="adjective1"><br>
<li>Verb Ending in "ED": <input type="text" name="verbEndingInED" id="verbEndingInED"><br>
<li>Noun (Plural): <input type="text" name="nounPlural1" id="nounPlural1"><br>
<li>Liquid: <input type="text" name="liquid" id="liquid"><br>
<li>Noun (Plural): <input type="text" name="nounPlural" id="nounPlural2"><br>
<li>Famous Person: <input type="text" name="famousPerson" id="famousPerson"><br>
<li>Place: <input type="text" name="place" id="place"><br>
<li>Occupation: <input type="text" name="occupation" id="occupation"><br>
<li>Noun: <input type="text" name="noun1" id="noun1"><br>
<li>Nationality: <input type="text" name="nationaltiy" id="nationality"><br>
<li>Female Celebrity: <input type="text" name="femaleCelebrity" id="femaleCelebrity"><br>
<li>Noun: <input type="text" name="noun2" id="noun2"><br>
<li>Female Friend: <input type="text" name="femaleFriend" id="femaleFriend"><br>
<li>Noun (Plural): <input type="text" name="nounPlural3" id="nounPlural3"><br>
<li>Number: <input type="text" name="number" id="number"><br>
<li>Adjective: <input type="text" name="adjective2" id="adjective2"><br>
<button id="finished">I'M FINISHED!</button>
</ul>
</div>
<div id="story"></div>
</body>
</html>
I know that my code practices are probably sloppy--I'm just trying to get it to work before I polish it up. Also, I have to use regular javascript and no jquery. I appreciate any help I get with this because I've been working in vain for hours and hours trying to figure out what's wrong.
Further to #Jaromanda X's suggestion, try wrapping your code in a function, and then assigning that function as the window.onload event handler.
This way your code won't run until the HTML document has been loaded. Otherwise your code might run before the document has loaded and there won't be any HTML elements to operate on.
function runOnLoad() {
// all your code in here
}
// assign your function as the handler for the onload event
window.onload = runOnLoad;
You might be interested to read this question for a bit more information about how to run code after the page has loaded, and a few different ways to do it.
pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it
You have errors in your code. bold() is not a function if you want to use bold text you can use <strong> tag.
Also if you want to get value from textbox you need to use value property.
function createStory() {
console.log("createStory HAS BEEN CALLED");
var finalStory = "";
finalStory += "I enjoy long, <strong>" + adjective1.value+ "</strong>";
story.innerHTML = finalStory;
console.log(story + " IS THE STORY");
}
I have corrected for the first textbox you can follow same for the rest.
You could use the addEventListener:
var div = document.getElementById('div');
function blah(e) {
}
div.addEventListener('click', blah);u
This would make a click event in the javascript. The e parameter is needed for this though because it calls for the event.
I am dynamically creating a table through Javascript and I DO want the table to continue off the right side of the page. Doing this manually lets the table continue off, but once I feed this into a for loop the <td>s wrap into a second line in the rendered HTML, creating two or more table rows when they reach the end of the page.
<div id="panelindex" style="overflow:scroll;text-align:center;">
<table border="0">
<tr></tr>
</table>
</div>
This is inside a table of its own (no style formatting). Then the Javascript:
var q = Math.floor((1/numpanels)*500);
if(q>50) q=50;
panelindex.innerHTML = "<table border='0'><tr>"
for(i=0; i<numpanels; i=i+1)
{
panelindex.innerHTML = panelindex.innerHTML + "<td><div id='panel" + i + "' onclick='jumppage(" + i + ")' style='float:left;text-align:center;margin:8px;border-width:3;border-color:white;border-style:none;'><a href='#" + i + "'><img src='thumbnails.php?image=blowem" + zeroFill(i,2) + ".gif&GIF&tw=128&th=128&quality=" + q + "'>\n" +
"<br />" + i + "</a></div></td>\n";
}
panelindex.innerHTML = panelindex.innerHTML + "</tr></table>"
You may notice that there is a <div> in the <td> and that is so I can apply a border marking the panel. Without the <div> it seems I cannot do that, and there are some other undesired effects. Any ideas what I can do so that all the <td>s end up on one line rather than split to a new line?
Example of what I want: http://edwardleuf.org/comics/jwb/009-conmet
What is happening: https://jsfiddle.net/w4uh0a3j/7/
Click the Show link.
innerHTML does not hold the string value you assign to it.
It parses the value as HTML, creates a DOM from it, inserts it into the document and then, when you read it back, it converts that DOM back into HTML.
This means that the string you assign is subject to error recovery and normalisation. In particular, the end tags you omitted are fixed.
panelindex.innerHTML = "<table border='0'><tr>"
console.log(panelindex.innerHTML);
<div id="panelindex" style="overflow:scroll;text-align:center;">
<table border="0"><tr>
</tr></table>
</div>
So when you start appending more data to it:
panelindex.innerHTML = panelindex.innerHTML + "<td>etc etc
You end up with:
<table border="0"><tbody><tr></tr></tbody></table><td>etc etc
Store your data in a regular variable. Only assign it to .innerHTML once you have the complete HTML finished.
A better approach then that would be to forget about trying to build HTML by mashing strings together (which is error prone, especially once you start dealing with characters that need escaping in HTML) and use DOM (createElement, appendChild, etc) instead.
OK,here is fixed html and js code. It seems like innerHTML fixes missing closing when updating html before all the code is building the rest of innerHTML. This code works :
<div id="panelindex" style="overflow:scroll;text-align:center;">
</div>
and js code :
var numpanels = 100;
var q = Math.floor((1/numpanels)*500);
if(q>50) q=50;
panelindex.innerHTML = "<table border='0'><tr>";
var html = "<table border='0'><tr>";
for(i=0; i<numpanels; i=i+1) {
html += "<td><div id='panel" + i + "' onclick='jumppage(" + i + ")' style='float:left;text-align:center;margin:8px;border-width:3;border-color:white;border-style:none;'><a href='#" + i + "'><img src='thumbnails.php?image=blowem" + ".gif&GIF&tw=128&th=128&quality=" + q + "'>\n" +
"<br />" + i + "</a></div></td>";
}
html += "</tr></table>";
document.getElementById("panelindex").innerHTML = html;
edit: Problem solved! I was modifying the page before it was loaded so the script didn't actually do anything. I fixed it now and it works. Thanks for the help, I'll have to chalk this one up to being new to jQuery and it's weirdness.
Long story short I'm trying to make a webpage that dynamically takes Article titles, thumbnail images, descriptions, and links to them, and creates a nicely formatted list on the page. I'm trying to accomplish this in jQuery and HTML5.
Here is the sample data that I'll be using to dynamically populate the page. For now formatting isn't important as I can do that later after it works at all.
<script>
var newsTitles = ["If It Ain't Broke, Fix It Anyways"];
var newsPics = ["images/thumbnail_small.png"];
var newsDescs = ["August 14th 2015<br/><b>If It Ain't Broke</b><br/>Author: Gill Yurick<br/><br/> Sometimes, a solution isn't the only one. So how do we justify changes to systems that don't need to be fixed or changed? I explore various systems from other successful card games and how their approaches to issues (be they successes or failures in the eyes of the deisgners) can help us create EC."];
var newsLinks = ["it_aint_broke-gill_popson.html"];
var newsIndex = 0;
var newsMax = 1;
The section of code where I'm trying to use the contents of the arrays above to dynamically fill elements.
<td style="height:500px;width:480px;background-color:#FFF7D7;padding:20px" colspan=2 id="article">
<h1>Articles</h1>
<!-- the column for each news peice add an element with the thumbnail, the title and teh desc -->
<script>
for(i = 0; i < newsMax; i++) {
$("#articleList").append("<h3 href="" newsLinks[i] + "">" + newsTitles[i] + "</h3>", "<img src=""newsPics[i] + "">","<p>" + newsDesc[i] + "</p>", ); $("div").append("hello");
}
</script>
<div id="articleList">
HELLO
</div>
</td>
Here is what it ends up looking like, I can post more info if needed as I am aware this may not be clear enough to fully explain my problem but I am unable to determine that. Thank you in advance.
try this
for(i = 0; i < newsMax; i++) {
$("#articleList").append("<h3 href=""+ newsLinks[i] + "">" + newsTitles[i] + "</h3>, <img src=""+newsPics[i] + "">, <p>" + newsDescs[i] + "</p>" ); $("div").append("hello");
}
Concatation issue + typo for newsDescs
The following string is invalid html and is missing a +
"<h3 href="" newsLinks[i] + "">"
You need to use proper quotes for html attributes, not "e;
Try
"<h3 href='" + newsLinks[i] + "'>"
OR
"<h3 href=\"" + newsLinks[i] + "\">" // `\` used to escape same type quote
Personally I prefer opening/closing html strings with single quotes but either will work
Note tht you should be getting a syntax error thrown in dev tools console which would have helped you locate problems
for(i = 0; i < newsMax; i++) {
$("#articleList").append("<h3 href='" + newsLinks[i] + "'>" + newsTitles[i] + "</h3>");
$("#articleList").append("<img src='" + newsPics[i] + "'>","<p>" + newsDesc[i] + "</p>" );
}
I am trying to pass a variable to the onClick function using a previously stored value. I have a database setup that searches for store locations when provided with a ZIP code. For example, the following link is generated using an ajax call after a user searches for a Zip Code. The returned value "WAFHOH3" is the ID that is associated with that particular store:
Generated Link:
<input type="button" onclick="myfunction(WAFHOH1);" value="This Is My Store" data-store-code="WAFHOH3">
Based on this code:
<div class="col-sm-3"><input type="button" onclick="myfunction(' + item.store_code + ');" value="This Is My Store" data-store-code="' + item.store_code + '"></div>
My problem is that if anything other than a number is returned I get a "Uncaught ReferenceError: WAFHOH3 is not defined" console error. When a number is passed like the example below, everything works fine and I get no errors and the application continues to work as expected.
For example (This Works):
Ive tried manually changing the character string to numbers only to isolate any database related issues. My only guess is that there is something in my code that is maybe attempting to verify the input as number.
The full code is below for the ajax call.
Full Code:
function myFunction() {
var searchValue = $('#foobar').val();
if (searchValue.length > 3) {
var acs_action = 'searchCction';
$.ajax({
async: false,
url: mysearchurl.url+'?action='+acs_action+'&term=' + searchValue,
type: 'POST',
data: {
name: searchValue
},
success: function (results) {
var data = $.parseJSON(results);
$('#resContainer').hide();
var html = '';
if (data.length > 0) {
html += '<br/><br/><ul>';
for (var i = 0; i < data.length; i++) {
var item = data[i];
html += '<li>';
html += '<div class="row myclass">';
html += '<div class="col-sm-9">';
html += ' <h3>' + item.label + '</h3>' ;
html += ' <span>' + item.desc + '</span>';
html += '</div>'
html += ' <div class="col-sm-3"><input type="button" onclick="dofunction(' + item.store_code + ');" value="This Is My Store" data-store-code="' + item.store_code + '"></div>';
html += '</div>';
html += '</li>';
}
html += '</ul><br/><br/><p>This is an example message please email us at admin#admin.com for assistance.';
}
else {
html += '<br/><br/><p>This is an example message, email us at admin#admin.com for assistance.';
}
$('#foo').html(html);
$('#foo').show();
$('.foobar').hide();
}
});
} else {
$('#foo').hide();
}
}
You need to wrap the input item.store_code with quotation marks; otherwise, it tries to treat it as a variable, not a string:
html += '<div class="col-sm-3"><input type="button" onclick="noActivationCodeRegistration(\'' + item.store_code + '\');" value="This Is My Store" data-store-code="' + item.store_code + '"></div>';
Ideally, you would attach a click handler after giving the buttons a class (such as register):
html += '<div class="col-sm-3"><input type="button" class="register" value="This Is My Store" data-store-code="' + item.store_code + '"></div>';
// Later
$('.register').on('click', function() {
var storeCode = $(this).data('storeCode');
noActivationCodeRegistration(storeCode);
});
I may be late, and maybe its an absolute mistake of me, but, i have to add my answer here because i just solved exactly the same situation in about three minutes ago .
I just solved this using the most simple sollution, and the error "Uncaught ReferenceError" from the console is solved, also i have my alert(); passing the variable as i needed.
I also need to include that i did not aproove the sollution gave, about "not using" the alert function, once i searched for the sollution, not for another method for that .
So, as i am using php, and the document is html, i thinked about the apostrophe charactere to the variable, after i had been spectating the element using chrome, first moving the function alert to the parent and child elements, that not solved .
After, also in the specting element, inside chrome F12 i tryed changing the function, including '' (that i passed in php code) into variable inside the alert function as: onclick="alert(variable);" to onclick="alert('variable');" and my alert had worked .
Ok. So, i try everything to insert '' 2 single quotes '' to my variable in php, that seems impossible, even if i change all my code to " and use ' or the oposite .
Then, i decided to try the most obvious and old school method, that is about charactere representation, and i cfound that ' (single quote) is represented by ' in php. Everything inside ->> ' <<-
My php code is like this : onclick="alert(''.$variable.'');"
It will work! (with no Vue), ok ? :)
I have a requirement that by clicking on a button, the printer dialog will open with the number of copies set to 2 instead of the default number 1.
No it is not possible using pure javascript with window.print().
However, if you are open to using Java Applet, take a look at qz-print aka jzebra. I have personally used this in some past projects for some advance printing requirements and the result is very satisfying. Take a look at their printHTML() method
***************************************************************************
* Prototype function for printing plain HTML 1.0 to a PostScript capable
* printer. Not to be used in combination with raw printers.
* Usage:
* qz.appendHTML('<h1>Hello world!</h1>');
* qz.printPS();
***************************************************************************/
function printHTML() {
if (notReady()) { return; }
// Preserve formatting for white spaces, etc.
var colA = fixHTML('<h2>* QZ Print Plugin HTML Printing *</h2>');
colA = colA + '<color=red>Version:</color> ' + qz.getVersion() + '<br />';
colA = colA + '<color=red>Visit:</color> http://code.google.com/p/jzebra';
// HTML image
var colB = '<img src="' + getPath() + 'img/image_sample.png">';
//qz.setCopies(3);
qz.setCopies(parseInt(document.getElementById("copies").value));
// Append our image (only one image can be appended per print)
qz.appendHTML('<html><table face="monospace" border="1px"><tr height="6cm">' +
'<td valign="top">' + colA + '</td>' +
'<td valign="top">' + colB + '</td>' +
'</tr></table></html>');
qz.printHTML();
}
Of course if you just want to print 2 copies, this may be way too over killed and too complicated to implement. But I'm not aware of any other way that can help you interfere with the browser's printing.