HTML showing the code as text instead of doing the function - javascript

I'm new to making websites, only got some notions of C++. So I have this code
in HTML:
<html>
<body>
<script type="text/javascript" src="http://localhost/Coin/wp-content/uploads/custom-css-js/77.js "></script>
<p>Click the button to trigger a function ".</p>
<button onclick="myFunction()">Generate question</button>
<p id="demo"></p>
<div id="quote"></div>
<script>
function myFunction()
{
document.getElementById("quote").innerHTML = showquote;
}
</script>
</body>
</html>
And this in JavaScript:
var myArray = ['Question 1', 'Test2', 'Practise 3'];
var rand = Math.floor(Math.random() * myArray.length);
function showquote(){
document.getElementById('quote').innerHTML = myArray[rand];
}
showquote();
When the button is clicked, this line appears:
function showquote(){ document.getElementById('quote').innerHTML = myArray[rand]; }
As I said, I'm just trying things in this languaje I barely know about, am I not invoking the function right? Thanks in advance.

function myFunction()
{
document.getElementById("quote").innerHTML = showquote;
}
should be
function myFunction()
{
showquote();
}
Click here for an executable demo of the solution above.
Reasoning
When you do
document.getElementById("quote").innerHTML = showquote;
You are assigning to the inner HTML the source code of the showquote function. Which is why you get function showquote(){ document.getElementById('quote').innerHTML = myArray[rand]; } (the source code of showquote) shown in the page.
So, what you really want to do is just call the showquote function, because that function alters the HTML alone. Thus the correct expression being showquote(), which invokes the showcode function.
Other improvements
Since now your myFunction is just a call to showquote:
function myFunction()
{
showquote();
}
Then you could actually remove it and use showquote directly in the HTML element.
<button onclick="showquote()">Generate question</button>
Another thing is, inside your JavaScript file, your first invocation of showquote, right after its declaration, in here:
function showquote() {
document.getElementById('quote').innerHTML = myArray[rand];
}
showquote(); // <----- this is the invocation I'm talking about
Is goint to yield an error. Simply because its code tries to find the element with id = quote (here: document.getElementById('quote')) and at the point this JavaScript code is executing, such element does not exist yet. Thus you getting an error at that point.
The solution is here is maybe just not call showquote at all. Or call it in a <script> tag right near the bottom of the HTML page, somewhere after the quote element is declared.

Related

Uncaught TypeError: google.script.run. is not a function

I have a code associated with a Google Spreadsheet, accessible via the script editor. In the code, I have a .gs file as the main body and I have an HTML file which is a sidebar used in the spreadsheet. I'm trying to call a function in the sheet.gs file from the HTML editor, would I do this using google.script.run.myFunction() in the HTML File, am I doing this wrong?
Basically in my sheet.gs I have
function myFunction() {
// do a thing
}
and in my HTML file I'm trying to call myFunction() like google.script.run.myFunction().
I have this function that is called by a button click
<div class="btn" onclick="generateSpreadsheetReport()">View Responses</div>
and the function is
function generateSpreadsheetReport() {
console.log("RUN!");
console.log("StudentAverage1");
var day = document.getElementById("day");
if (!day.value) day.value = "";
var course = document.getElementById("courses");
var stud = document.getElementById("stud");
console.log(day.value,course.value,stud.value)
google.script.run.withSuccessHandler(displayAverage).sortByParameter(day.value||"", course.value||"", stud.value||"");
console.log("StudentAverage2");
google.script.run.getStudentAverage(); // <----- This line right here isn't working.
}
And then in my sheet.gs I have a function called getStudentAverage() which is defined and it shows up in the library when I click on it from the resources page. So I Assume I am calling it wrong in my HTML
Not sure what your problem is, but from the looks of it in your sheet.gs try changing your
myFunction() {
// do a thing
}
to
function myFunction() {
return true;
}
It's just a wild guess based on the problem you've explained. Try this and let us know if it works for you.
Update: from your HTML file invoke myFunction() like
function myFunction() {
return true;
}
google.script.run.withSuccessHandler(function(myparam){
console.log("Response: "+myparam);
}).myFunction();

Why is my javascript code going into an infinite loop?

In the code below, whenever I click on the submit button, multiple window's open up as it it were in infinite loop. If I uncomment alert, then multiple alerts keep popping like they were in infinite loop. Why could this be happening ?
<html>
<head>
<script type = "text/javascript">
var window;
function moveBy() {
//alert("-- hello ---");
window = window.open("http://www.w3schools.com");
window.moveBy(10, 20);
}
</script>
</head>
<body>
<input type = "submit" value = "moveBy" onclick = "moveBy()"> </input>
</body>
</html>
Javascript does not support method overloading, so by calling window.moveBy(10, 20); you are actually basically calling moveBy() again, resulting in an infinite loop.
Calling a function from itself is called recursion. The linked post is a good read on this topic, and will guide you on where you might want it. But in your case you clearly don't.
Have a read of this article for more detail.
To prevent this from happening, you can rename your moveBy() function to myMoveBy() or better openAndMoveBy()
Because you call function moveBy from itself.
You are creating a recursion (function that calls itself) by calling window.moveBy inside your moveBy function without stating a break point or exit case:
function moveBy() {
//alert("-- hello ---");
window = window.open("http://www.w3schools.com");
window.moveBy(10, 20); //recursion, it will call this function over and over again.
}
Maybe what you want is to use another name for your function and call the actual window.moveBy inside with predefined parameters:
function customMoveBy() {
//alert("-- hello ---");
window = window.open("http://www.w3schools.com");
window.moveBy(10, 20);
}
<input type = "submit" value = "moveBy" onclick = "customMoveBy()"> </input>
The problem is that you are calling the function moveBy inside the funtion moveBy. Whenever you execute the function you call it again and again ...
Try this:
<html>
<head>
<script type = "text/javascript">
var window;
function moveBy() {
alert("-- hello ---");
window = window.open("http://www.w3schools.com");
//window.moveBy(10, 20);
}
</script>
</head>
<body>
<input type = "submit" value = "moveBy" onclick = "moveBy()"> </input>
</body>
</html>

Calling javascript function in html second time

Below is my code for a simple text based game that i am trying to make but i cannot understand why the first time i call my function with a hyperlink 'link1', it works but when i add another link to my html document using javascript, and try to call another function onclick upon that link, it doesn't work. can somebody explain?
var getupvar = document.getElementById("attack");
getupvar.onclick = attack;
function attack() {
$('<p> Some text </p>').insertBefore("#placeHolder");
$('link2').insertBefore("#placeHolder");
}
var link2event = document.getElementById("defend");
link2event.onclick = defend;
function defend() {
alert("working now");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="console">
<p id="startGameMessage"></p>
<div id="gameArea">
<p id="gameMessage">Some Text</p>
link1
<div id="placeHolder"></div>
</div>
</div>
When you link up your attack onclick, the element exists. But because #defend does not exist on the dom when you run var link2event = document.getElementById("defend");, your onclick never gets set.
Instead try:
var getupvar = document.getElementById("attack");
getupvar.onclick = attack;
function attack(){
$('<p> Some text </p>').insertBefore("#placeHolder");
$('link2').insertBefore("#placeHolder");
var link2event = document.getElementById("defend");
link2event.onclick= defend;
}
function defend(){
alert("working now");
}
jsfiddle https://jsfiddle.net/fv9mpbm6/
This will get your code working how you wish. If you don't do so, your code cannot work because the two lines added to the attack() function will be executed when you call the .js file in your html document as a script and not as a function. This means that the method getElementById("defend") will not find anything, because when you initialize the page, you cannot find any element with this id, you create it when you click on the link.
But do note that if you click attack more than once, your code will break because there will be more than one defend element.
When creating dynamic content, never use ids for handlers! Use classes instead
function attack() {
$('link2').insertBefore("#placeHolder");
}
Also, to ensure proper handling for elements that may not exist yet, leverage jquery's on functionality
$('body').on('click', '.defend', function() {
alert("working now")
})
it is simple, just put the two lines of code
var link2event = document.getElementById("defend");
link2event.onclick= defend;
inside the attack() function, at the end,and it works. This is the new attack() function:
function attack(){
$('<p> Some text </p>').insertBefore("#placeHolder");
$('link2').insertBefore("#placeHolder");
var link2event = document.getElementById("defend");
link2event.onclick= defend;}
If you don't do so this code cannot works because these two lines will be executed when you call the .js file in your html document as a script and not as a function. This means that the method getElementById("defend") will not find nothing, because when you initialize the page, you cannot find any element with this id, you create it when you click on the link.
I hope that this helps!
Cheers!
Try this, I am not sure is this what you expect
var getupvar = document.getElementById("attack"), i=0;
getupvar.onclick = attack;
function attack() {
$('<p> Some text </p>').insertBefore("#placeHolder");
$('link2').insertBefore("#placeHolder");
var link2event = document.getElementById("defend"+i);
link2event.onclick = defend;
i++;
}
function defend() {
alert("working now");
}

is there any way to print a javascript result into the div where the javascript function is being called?

I am wondering if is possible to do this.
I have my javascript function
function doSomething(){
return "Hello World"; //its actually more complicated method but the logic is the same..
}
so, at my html I have this.
<div class="someClass">
<script type="text/javascript">
doSomething();
</script>
</div>
So, basically, I want to is to print that hello world inside the div where is called.
Any idea how to do this?
AFAIK JavaScript cannot easily determine the location of its script declaration. As Marc B suggested in a comment--it works for printing to the document stream, but other applications won't work. Not to mention if you want the same behavior in multiple places, you've violated the "don't repeat yourself" (DRY) principle. You should instead inspect the dom document and find the element you wish to print "hello" in. This is easily accomplished with jQuery:
$(document).ready(function () {
$('.someClass').text('hello');
});
As laugri suggests, you should add an id to your div if you want only the one div changed.
<div id="someId".../>
...
$(document).ready(function () {
$('#someId').text('hello');
});
You can generate a unique div to find wherever you're code is executing
http://jsfiddle.net/190p77wu/
var doSomething = function (id) {
var targ = document.getElementById(id).parentNode;
targ.innerHTML = "This was inserted for id " + id;
}
and your html:
<div>
You shouldn't see this text.
<script>
var uniqueId = "tmp_" + Math.round(Math.random() * 100000000);
document.write('<div id="' + uniqueId + '"></div>');
doSomething(uniqueId);
</script>
</div>
Edit: or even cooler, if you have a properly cached JS file, you can do something like this:
http://jsfiddle.net/190p77wu/1/
var doSomething = function (script) {
var targ = script.parentNode;
targ.innerHTML = "This was inserted dynamically";
}
and this html:
<div>
You shouldn't see this text.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js" onload="doSomething(this)"></script>
</div>
Try setting an id at script element , calling script.parentElement within doSomething
<div class="someClass">
<script type="text/javascript" id="someClass">
function doSomething() {
var elem = document.getElementById("someClass");
elem.parentElement.appendChild(
document.createTextNode("Hello World")
)
}
doSomething();
</script>
</div>

Javascript Calculation function - Not calculating in html

I am having an issue implementing this calculator on my website which i created. I think i have used the wrong javascript to create the simple calculation which is the following math calculation: ((list price - rrp) / list price) * 100
PLEASE NOTE, i am aware of the values not being numbers, please replace them with any numbers. it still doesnt work.
This is to get the percentage value of the discount against the list and the RRP.
Please review the code before HTML:
<script type="text/javascript">
discountFinal(#OriginalPrice, #ListPrice);
</script>
<div id="discountCode">
<span id="spanish"></span>
<span id="spanishtwo">%</span>
</div>
Javascript:
var discountFinal = function (firstly, secondly) {
var totalfirst = secondly - firstly;
var totalsecond = totalfirst / secondly;
var totalthird = totalsecond * 100;
if (document.getElementById("discountCode").innerHTML === null) {
document.getElementById("spanishtwo").innerHTML.replace("%", "")
} else {
document.getElementById("spanish").innerHTML = Math.floor(totalthird / 5) * 5
}
};
I dont think i am calling the function within the html properly. Can someone assist with this please.
http://jsfiddle.net/xwzhY/
I'm not sure the error you're getting, but it seems as if you're calling the discountFinal function before it's defined. When you move the call, it starts to work:
http://jsfiddle.net/bmonty/xwzhY/4/
Edit after comment from OP.
You just need to make sure your discountFinal function is defined at the top of your page, before any place it gets called.
This will work:
<script type="text/javascript">
var discountFinal = function(a, b){};
</script>
<script type="text/javascript">
var result = discountFinal(1, 2);
</script>
But this will throw an error:
<script type="text/javascript">
var result = discountFinal(1, 2);
</script>
<script type="text/javascript">
var discountFinal = function(a, b){};
</script>
To get some clarification, View Source on the HTML page from your browser to see what the resulting page looks like. That should point out where the order of operations is getting messed up.
It works fine if you call your function after it exists: http://jsfiddle.net/xwzhY/2/
Just make sure that the function is declared earlier in the code than you use it. Or declare it using a function statement rather than a function expression assigned to a variable:
function discountFinal(firstly, secondly){
...
Trying put "" around your perl variable, you need to pass the value

Categories