Javascript Calculation function - Not calculating in html - javascript

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

Related

Set height and width for popup window in variable (syntax issue probably)

I got the basics of my javascript to function with help I got here on Stackoverflow. I see a bit of room for improvement on what I have now though. A lack of Javascript knowledge keeps me stuck unfortunately.
I'm trying to set arguments such as width, height, toolbar, status for a popup window in a variable. I tried every way I could find both here and via Google to get the syntax right but whatever I try it doesn't seem to work.
See below in Function1 what I ended up with (Function2 still has the hardcoded parameters that I'm trying to put in the variable called windowSpecs).
var windowSpecs = "\'toolbar=no,status=no,scrollbars=yes,resizable=yes,top=500,left=500,width=600,height=745\'";
var function1Name = "test_function_1";
var function1Url = "https://www.google.com";
var function1Class = ".test_function_class1";
var function2Name = "test_function_2";
var function2Url = "https://www.cnn.com";
var function2Class = ".test_function_class2";
// Function 1
window[function1Name] = function () {
window.open(function1Url, windowSpecs,"_blank",);
}
jQuery(function1Class).click(function() {
window[function1Name]();
});
// Function 2
window[function2Name] = function () {
window.open(function2Url, "_blank", "toolbar=no,status=no,scrollbars=yes,resizable=yes,top=500,left=500,width=600,height=745");
}
jQuery(function2Class).click(function() {
window[function2Name]();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Any pointers that could help me figure this out would be greatly appreciated!

Changing image SRC using javascript - unknown error

I'm using javascript for the first time and am having difficulty getting certain features to work. Crucially I can't seem to get the following line of code to execute.
document.getElementByID("reportImage").src=filepath;
The full code is given below.
Notice that I've created a test function to try and narrow down the cause of the malfunction. The first two functions are there to demonstrate intent but are not currently being called by the .
The behavior of the test function suggests that the error is within this specific line. Notably the alert will fire if it is placed first in the function but will not trigger if placed second (suggesting that this specific line is problematic in some way).
It may be a simple syntax error but I've checked many times and can't see what it might be. Please help!
<!DOCTYPE html>
<html>
<script>
/* declare and set script variables */
var numberOfImages, imageArray, timing, containingFolder, i;
i = -1;
timing = 3;
containingFolder = "H:\\Images";
imageArray = [
"FoxKey.jpg",
"TeamKPI2.tif"
]; //imageArray should contain names of image files that sit within the specified folder
numberOfImages = imageArray.length;
function activateImageTimer() {
/* function iterates through selected images */
if (numberOfImages === timingArray.length) {
setInterval(nextImage(), timing*10);
}
else { alert("Please check contents of imageArray and timingArray. The
number of images should correspond to the number of timings."); }
}
function nextImage() {
i = (i+1) % numberOfImages; //use modulus function to loop through array
var filepath = containingFolder + "\\" + imageArray[i]; //build filepath
document.getElementByID("reportImage").src=filepath;
}
function testFunction() {
document.getElementByID("reportImage").src="H:\\Images\\FoxKey.jpg";
alert("Function is functioning");
}
</script>
<body onload="testFunction()">
<img id="reportImage" src="H:\Images\TeamKPI2.tif">
</body>
</html>
JavaScript is Case Sensitive.
Try with this:
Change: document.getElementByID to document.getElementById
And, <script></script> it has to be put inside the body or head, not of html.

HTML showing the code as text instead of doing the function

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.

JavaScript/jQuery - Multiple Wack-a-Mole Qs: (Increment Score, x/y positioning, click event listener - corrected)

I'm a beginner, obviously, and working on a project for class. I managed to solve 1 step through the site & 1 on my own, but the last 4 are getting more confusing the more I search through these other questions, which I've been doing all day and most of yesterday. I've gone through W3Schools, TutorialsPoint, and tizag.com and still can't figure it out.
Here are the instructions:
Write two functions that generate random whole numbers. One function should return numbers between 0 and 300 (for the y positioning) and the other should return numbers between 0 and 600 (x positioning). Call them (temporarily) from the jQuery ready function and alert() the values.
In the jQuery ready function, write some Javascript/jQuery code which adds a jQuery click event listener to button#start_button. For the time being, add an alert() to test that the button click is working.
Create a function (outside the jQuery ready function) which increments the user's score when called and updates the HTML in span#score. Hint: You should create a global variable to keep track of the score.
Call your score increment function within Document Ready for testing purposes.
This is what I have. Any help would be greatly appreciated. I'm very frustrated.
var mole='<img src="img/mole.jpg"/>'
var score=docutment.getElementById("#score");
$(document).ready(function() {
$("#gamespace").show().html(mole);
$("#timer").show()
document.getElementById("start_button").addEventListener("click", myFunction);
function myFunction(){
alert(Okay);
}; //end alert
}); //end.ready
function getRndInteger(min, max){
var y=Math.floor((Math.random()*300)+1);
function click(){
alert(y);
}; //end alert y
}; //end y
function getRndInteger(min, max){
var x=Math.floor((Math.random()*600)+1);
function click(){
alert(x);
}; //end alert x
}; //end x
function displayScore(){
score.innerHTML=
}; //end score
I guess I should add the rest of the code if anyone whats to test it out.
<div id="content">
<h1>Whack-A-Mole</h1>
<p>After clicking "start", you will have 30 seconds to click
as many moles as you can. The moles appear randomly so be ready! </p>
<div id="controls">
<span id="score">0 pts</span>
<button type="button" id="start_button">Start!</button>
</div>
<div id="timer">30 seconds left</div>
<div id="gamespace">
</div>
</div>
Fixed it!
<script>
var mole='<img src="img/mole.jpg"/>';
var score=0;
$(document).ready(function(){
$("#gamespace").html(mole);
$("#score").click(increment);
$("#timer").show();
$("#start_button").click(function(){
alert("Okay");
}); //end alert
alert(getRndNum());
alert(getRndNumY());
}); //end.ready
function getRndNum(min, max){
var x=Math.floor((Math.random()*600)+1);
return x;
}; //end x
function getRndNumY(min, max){
var y=Math.floor((Math.random()*300)+1);
return y;
}; //end y
function increment(){
$("#score")[0].innerHTML=score;
}; //end increment
</script>
Here are some comments on your code:
Don't forget to end all your lines with semi-colons
var mole='<img src="img/mole.jpg"/>'
Make sure your spelling is correct ('document' is misspelled).
var score=docutment.getElementById("#score");
You're also mixing jQuery and vanilla JavaScript here. To get the element using vanilla JavaScript, you would write the following (note the lack of a # symbol):
var score = document.getElementById('score');
Whereas using jQuery you would write:
var score = $('#score');
'#gamespace' and '#timer' are already visible, so no need to call .show() on them.
$("#gamespace").show().html(mole);
$("#timer").show()
Again, you can use jQuery here:
// JavaScript
document.getElementById("start_button").addEventListener("click", myFunction);
// jQuery
$('#start_button').click(myFunction);
This will look for a variable named Okay. If you want to show the text 'okay', you need to wrap it in quotes.
function myFunction(){
alert(Okay);
}; //end alert
Here, you're defining two functions with the same name, so your second one is overwriting your first.
function getRndInteger(min, max){
// do stuff...
}; //end y
function getRndInteger(min, max){
// do stuff...
}; //end x
You're also not returning any value from the function. You're defining a function called 'click', but you're never calling it or binding it to anything. You're also taking in two parameters (min and max) which you don't use.
function getRndInteger(min, max){
var y=Math.floor((Math.random()*300)+1);
function click(){
alert(y);
}; //end alert y
}; //end y
To write a function that just returns a value from 0 to 300, you would do this:
function randomX(){
var x = Math.floor(Math.random()*300);
return x;
}
You could alert an outcome of randomX by writing
alert(randomX());
I hope that helps you with cleaning up the code you already have, the jQuery documentation is very helpful and will give you an idea of what parameters you need to pass into certain functions, what they do, and what they'll return.

How to make a html random redirect

How I would go about making a website that randomly redirects between multiple (in this case 2) websites?
Obviously what is below doesn't work due to what I hope is the meta tag; I would like to know if the javascript code is the correct way to do this
and how it would work.
<head>
<meta http-equiv="refresh" content="1;url=http://example1.com">
<script type="text/javascript">
if Math.random() =< 0.5;
window.location.href = "http://example1.com/"
else;
window.location.href = "http://example2.com"
</script>
<title>Page Redirection</title>
</head>
your javascript syntax inside script tag is not correct either
<script type="text/javascript">
if ( Math.random() <= 0.5 ) //proper parenthesis surrounding the condition and also < will come before =
window.location.href = "http://example1.com/";
else //semicolon removed from here
window.location.href = "http://example2.com";
</script>
You did it right (almost), Wrap the condition in () and remove ;, it will break the if.
if (Math.random() =< 0.5)
window.location.href = "http://example1.com/";
else
window.location.href = "http://example2.com";
Keep in mind one little fact.
if(false)
alert(1);
Won't alert anyting as the if condition is always false. But if you see
if(false); // If will break here.
alert(1);
Will always alert as if breaks and then the execution proceeds without if.
You could make the function a little bit more generic:
var sites = [
'http://www.dilbert.com',
'http://stackoverflow.com',
'http://Starwars.com'
];
var target = Math.floor(Math.random() sites.length);
window.location = sites[target];
So when your site collection grows you don't need to alter the code. You could even pack it into a function:
function goRandomSite(sites) {
var target = Math.floor(Math.random() sites.length);
window.location = sites[target];
}
Hope that helps

Categories