I have gindex.html, content is JavaScript game, this game give me the result in:
<span id="success"></span>
Now I included gindex.html in index.html using iframe this code:
document.getElementById('quiz').innerHTML = '<h4 id="qnr">○ question number.'+ (nquiz + 1) +'</h4><iframe id="iframei2" src="indexg.html"></iframe><button id="nextq" onclick="obTrivia.sQuiz(\'next\')">next</button>';
and import (get) the success by:
var mygrade = document.getElementById("iframei2").contentWindow.document.getElementById("success");
then I used if to know (Right or Wrong):
if (mygrade >= 7) {
nia++; // Wrong
}else if (mygrade < 7) {
nca++; // Right
}
the problem is the result of if is "Right" every time?!
You need to get the text of the span and compare that:
if (mygrade.innerText != "" && parseInt(mygrade.innerText, 10) >= 7)
Related
I'm working on a site where users can paste in embed codes from the likes of twitter, youtube, instagram, facebook, etc. The Embed code is validated and saved if valid.
The users can then see and edit the code and this is where some code fails validation. E.g. Twitter embed codes may contain < (aka '<') in the post name/text. When pasting in the code originally it passes validation as it contains <, but when displaying the code back to the user the browser shows < in the textarea and this is then submitted if the user clicks save. Our validation function treats this as the start of a tag and the validation fails.
Possible solution 1:
Better validation. The validation we use now looks like this It basically finds the tags (by looking for '<' etc) and checks that each open tag has a closing tag. There must be a better/standard/commonly used way:
(function($) {
$.validateEmbedCode = function(code) {
//validating
var input = code;
var tags = [];
$.each(input.split('\n'), function (i, line) {
$.each(line.match(/<[^>]*[^/]>/g) || [], function (j, tag) {
var matches = tag.match(/<\/?([a-z0-9]+)/i);
if (matches) {
tags.push({tag: tag, name: matches[1], line: i+1, closing: tag[1] == '/'});
}
});
});
if (tags.length == 0) {
return true;
}
var openTags = [];
var error = false;
var indent = 0;
for (var i = 0; i < tags.length; i++) {
var tag = tags[i];
if (tag.closing) {
// This tag is a closing tag. Decide what to do accordingly.
var closingTag = tag;
if (isSelfClosingTag(closingTag.name)) {
continue;
}
if (openTags.length == 0) {
return false;
}
var openTag = openTags[openTags.length - 1];
if (closingTag.name != openTag.name) {
return false;
} else {
openTags.pop();
}
} else {
var openTag = tag;
if (isSelfClosingTag(openTag.name)) {
continue;
}
openTags.push(openTag);
}
}
if (openTags.length > 0) {
var openTag = openTags[openTags.length - 1];
return false;
}
return true
};
}
Possible solution 2:
Encode the text containing '<' (i.e. textLine.replace(/</g, '<')) without encoding tags like <blockquote class="...>.
I've been experimenting with something like:
$(widget.find("textarea[name='code']").val()).find('*')
.each(function(){
// validate $(this).text() here. Need to get text only line by
// line as some elements look like <p>some text <a ...>text
// </a>more text etc</p>
});
Possible solution 3:
Display < as < and not < in the browser/textarea. We use icanhaz for templating (much like moustache).
Using date.code = '<' with <textarea name="code">{{{code}}}</textarea> in the template does not work, neither does {{code}}.
So I played some more and the following works, but I am still interested in suggestions for better embed code validation or better answers.
After the edit form (inc textarea) code is created using the icanhaz template (i.e. after widget = ich.editEmbedWidgetTemplate(encoded_data);) I do the following to encode instances of < etc into < etc. ' has to be encoded manually using replace.
var embedCode = '';
$( widget.find("textarea[name='code']").val() )
.filter('*')
.each(function(){
embedCode += this.outerHTML.replace(/'/g, ''');
});
widget.find("textarea[name='code']").val(embedCode);
Im quite new at javascript so dont expect me to know much else than whats written :)
So i have a javascript file with a lot of javascript codes that almost looks the same except a number is changing with each element.
Most of my code are inside a function just not written since it's a cut out.
The relevant part of my code looks something like:
//Upgrade 1
if (CREDITS >= UpgradePrice1 && Upgrade1 === 0){
document.getElementById("Upgrade1").style.display = "block";}
else{document.getElementById("Upgrade1").style.display = "none";}
//Upgrade 2
if (CREDITS >= UpgradePrice2 && Upgrade2 === 0){
document.getElementById("Upgrade2").style.display = "block";}
else{document.getElementById("Upgrade2").style.display = "none";}
//Upgrade 3
if (CREDITS >= UpgradePrice3 && Upgrade3 === 0){
document.getElementById("Upgrade3").style.display = "block";}
else{document.getElementById("Upgrade3").style.display = "none";
And so on...
The values are assigned in a file named StandardValues.js:
var UpgradeName1 = "Craftmanship Lvl 1";
var UpgradePrice1 = 100;
var UpgradeContent1 = "+100% Gods Hands! <br> +20% Blessed Farmer!";
var Upgrade1 = 0;
var UpgradeName2 = "Craftmanship Lvl 2";
var UpgradePrice2 = 200;
var UpgradeContent2 = "+100% Gods Hands! <br> +20% Blessed Farmer!";
var Upgrade2 = 0;
And so on...
If it were a html code i tried to generate i would use a php while function and make it echo the same code with the changed number a specefic amount of times.
But since this is inside a javascript file i really dont think thats an option?
The javascript code from before is in a .js file.
I think a potential fix could be:
Inside a .php file:
<?php
$Upgrades = 10;
$CurrentUpgrade = 1;
while ($Upgrades >= $CurrentUpgrade){
echo "
<script>
function Upgrade1(){
//Upgrade ".$CurrentUpgrade."
if (CREDITS >= UpgradePrice".$CurrentUpgrade." && Upgrade".$CurrentUpgrade." === 0){
document.getElementById('Upgrade".$CurrentUpgrade."').style.display = 'block';}
else{document.getElementById('Upgrade".$CurrentUpgrade."').style.display = 'none';}
}
</script>
";
$CurrentUpgrade ++;
}
?>
*Sry for any typo in this part, made it quite quick.
But i would quite like to keep the javascript code inside my .js file instead of having it in my .php file.
So to sum it up i would like to (If possible):
Keep all code inside the .js file
Generate javascript code with javascript code
Repeat the same javascript element with only a number changing with each element
Try to shorten the amount of code by doing this.
Still be able to use any of the assigned variables alone somewhere like in a buy function.
I hope i gave all relevant information :)
Thanks in advance.
You can create a method (in index you are passing the number in the end of your variables):
function myFunction(newUpgradePrice, newUpgrade, index) {
if (CREDITS >= newUpgradePrice && newUpgrade === 0){
document.getElementById("Upgrade" + index).style.display = "block";}
else{document.getElementById("Upgrade" + index).style.display = "none";
}
Is This what you are looking for? Anything needing to be changed to meet your needs?
This is my code, I am trying to do an animation with 8 pictures, I was thinking first that the error is because the images are .jpg, but i tryed even converting them to .gif format and the code still did not work, When I try to run the code, i get an error saying: "Cannot set property 'src' of undefined", I don't see any mistakes in the code, i tryed looking at it multiple times, please if someone can help, thanks.
G:\Year 2\OOD - object oriented development\Webpages\Assignment\Explosion
<script>
var explosion = new Array(8);
var c = 0;
var startExplode;
var i = 0;
explosion[0] = 'ex1.jpg'
explosion[1] = "ex2.jpg"
explosion[2] = "ex3.jpg"
explosion[3] = "ex4.jpg"
explosion[4] = "ex5.jpg"
explosion[5] = "ex6.jpg"
explosion[6] = "ex7.jpg"
explosion[7] = "ex8.jpg"
function explode()
{
if(c == 7 | (i > 0 & i <= 1))
{
c = 0;
}
else
{
c++;
document.animation.src = explosion[c];
}
}
</script>
<body>
<form>
<img src ="ex1.jpg" name = "explosion" position = "fixed">
<input type="button" name="startExplode" value="explode"
onClick="startExplode=setInterval('explode()',20);">
</form>
</body>
</html>
There are a couple of problems with the code:
In the function, the AND and OR operators are doubled, not singles:
if(c == 7 | (i > 0 & i <= 1))
SHOULD BE:
if(c == 7 || (i > 0 && i <= 1))
NEXT, you are not referring to the image tag properly, so the SRC will not update, in addition, the image is call "explosion", not "animation", at least in your HTML. Also, if you give the image tag an ID, you can refer to the ID (much easier).
So the code:
document.animation.src = explosion[c];
<img src ="ex1.jpg" name = "explosion" position = "fixed">
SHOULD BE:
document.getElementById("explosion").src=explosion[c];
<img src="ex1.jpg" name="animation" position="fixed" id="explosion">
I hope this helps!
What is the most convenient way of injecting a number into the HTML of the site (using Chrome Extensions), when the given parameter is found in the website's code? For example we have a list:
www.newsweek.com, hf-title, 2
www.aaa.com, yzs, 1
www.ccc.com, abc, 123
When we find "hf-title" on the website www.newseek.com then number "2" is inserted next to the found paragraph on the website in the browser. When we find "abc" in the code of the website www.ccc.com then number "123" is inserted next to the table, and so on.
There cannot be any connection to the database, just javascript.
The list that is going to be used will be hundreds of rows long, so it is really problematic to use switch statement.
The source table has to be located in the Google Chrome extension files on the PC. The information should be looked for when (or shortly after) the site is being opened.
Example of the source code:
<h2 class="hf-title">
Four NATO Allies Deny Ukraine<span class="overlay article-overlay"></span>
</h2>
<div class="hf-summary">
NATO officials have previously said... </div>
</div>
We add simply
<a> 2 </a>
at the end.
Any ideas? ;)
What you will likely need to do is find all of the text nodes on the page. From there you can begin editing them. The 'modifyTextNodes' function is an example of using a TreeWalker to do this. It is a very efficient method for traversing the DOM.
var arr = [{url:"www.newsweek.com", string:"hf-title", value:"2"},
{url:"www.aaa.com", string:"yzs", value:"1"},
{url:"www.ccc.com", string:"abc", value:"123"}];
function modifyTextNodes() {
var el = document.getElementsByTagName('html')[0];
var walk=document.createTreeWalker(el,NodeFilter.SHOW_TEXT,null,false);
while(n = walk.nextNode()) {
modifyNode(n);
}
}
function modifyNode(node) {
if (node.nodeType == Node.TEXT_NODE && node.parentNode != undefined && (val = node.nodeValue.trim())) {
var addToEnd = "";
for (var i=0; i<arr.length; i++) {
if (document.baseURI.indexOf(arr[i].url) > -1 && val.indexOf(arr[i].string) > -1) {
addToEnd += arr[i].value;
}
}
}
if (addToEnd) {
node.nodeValue += addToEnd;
}
}
Alternatively, if it is elements that you are trying to find, you could use querySelectorAll to find all the matching elements.
document.querySelectorAll("[class='" + arr[i].string + "']");
In this case 'modifyAllNodes' would look like
function modifyAllNodes() {
for (var i = 0; i<arr.length; i++) {
if (document.baseURI.indexOf(arr[i].url) > -1) {
var nodes = document.querySelectorAll("[class='" + arr[i].string + "']");
modifyNodes(nodes, arr[i]);
}
}
}
function modifyNodes(nodes, arrEl) {
for (var i=0; i<nodes.length; i++) {
if (node.nodeValue.indexOf(arrEl.string) > -1) {
node.nodeValue += arrEl.value;
}
}
}
first you have to know the structure of the list you are trying to "hack", which means the ID or class names. Afterwards, in your JS check each record of that list if its content matches the string you pass to and then do a .append()
I have a string array(APN) in my bean(accessed as header). I am accessing it like this
<c:forEach var="apn" items="${header.APN}" >
var g = apn;
if (g.length!=0 && g!="null"){
if(counter == 1){
count=0;
$("#img0").show();
$("#apn0").show();
$("#rtu0").show();
}
if(counter == 2){
count=1;
$("#img0").hide();
$("#apn0").show();
$("#rtu0").show();
$("#img1").show();
$("#apn1").show();
$("#rtu1").show();
$("#removeimg1").show();
}
if(counter == 3){
count=2;
$("#img0").hide();
$("#apn0").show();
$("#rtu0").show();
$("#img1").hide();
$("#apn1").show();
$("#rtu1").show();
$("#removeimg1").hide();
$("#img2").show();
$("#apn2").show();
$("#rtu2").show();
$("#removeimg2").show();
}
}
</c:forEach>
When I keep an alert after
var g = apn;
Alert is not popped up. I have some text boxes in my UI. When I press on + icon(rendered in the form of image), another set of text boxes appear to enter multiple values. My code is not working. Can anyone help me out
I think your assignation part is incorrect. Try this -
var g = ${apn};
Seems you need an } just before /c:out. I don't know if this is the cause of your problem, i just noticed it.