Javascript random number not displaying result - javascript

I've got a webpage which is meant to generate a random number, then when the number =5 it displays a win message..if not display lose message, but its not displaying any alerts..have i missed something out?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function WinLose()
{
var x=document.getElementById("demo");
x=x.innerHTML=Math.floor((Math.random()*5)+1);
return x;
if (x=4)
{
alert("winner!");
}
else
{
alert("loser");
}
}
</script>
</head>
<body>
<p id="demo">Click the button to display a random number between 1 and5.</p>
<button onclick="WinLose()">Try it</button>
</body>
</html>
EDIT:
Managed to get this bit working so now it displays either win or loose depending on its number, yet does anyone know how i can swap the alerts in the if statements to display a DIV section. ive got a jQuery file included so it can accept the hide/show effect...anything i tried didnt work

you have return x after you generate a random value for x. this means no javascript code after that line will run in that function.
also, your if statement needs to use '==' to do the comparison rather than '=' which is assignment.

Yeah, It can be tough. The main problem again has to be other than return x is the "==". So this
if (x=4)
Should really say:
if (x==4)
What you said before was that you were assinging x to 4 so that has no meaning at all and messes everything up.
Hope this helps you!

You need to return x after you generate the random value; and you must add x == 4
function WinLose()
{
var x=document.getElementById("demo");
x=x.innerHTML=Math.floor((Math.random()*5)+1);
if (x==4) {
alert("winner!");
} else {
alert("loser");
}
return x;
}
DEMO

Your code:
x=x.innerHTML=Math.floor((Math.random()*5)+1);
x is receiving x.innerHTML then x.innerHTML = random number.
Correct way: (remove "x=")
x.innerHTML = Math.floor((Math.random()*5)+1);

Here is a simplified version that externalizes the alerts (I assume you don't plan to use them later)
function WinLose(){
var x=Math.floor((Math.random()*5)+1);
document.getElementById("demo").innerHTML=x;
return (x==5) ? "Winner!" : "Loser";
}
alert(WinLose());

Related

I want to print counting from 1 onwards using setInterval function of JavaScript but it's giving the output as 0 continuously.

I want to print counting from 1 onwards using setInterval function of JavaScript but it's giving the output as 0 continuously.
My code is:
<html>
<body>
<script> //javascript starts
var x=0;
function f(){
document.write(x);
x++;
}
setInterval(f,500); //need to output as 0 then 1 and so on.
</script>//javascript ends
</body>
</html>
Your code actually works as is, you just need to ensure that you are handling the result properly.
Right now, you are using document.write() to output, which means you are having all the numbers display one next to another. You can use a <p> tag with a specified id to replace every time instead, so it only displays one number at a time!
That code could look like:
<html>
<body>
<script> //javascript starts
var x=0;
function f(){
document.getElementById("demo").innerHTML = x;
x++;
}
setInterval(f,500); //need to output as 0 then 1 and so on.
</script>
<p id="demo"></p>
</body>
</html>
Demo Fiddle
Hope it helps!
Here you go with the solution https://jsfiddle.net/7vquztks/2/
var x = 1;
setInterval(function(){
document.write(x);
x++;
}, 500);

Trying to change button's contents each hit fails

Given the code :
<html>
<head>
<script src="jquery-2.1.0.min.js"></script>
Something...
</head>
<button id='flip' type='button'>Flip</button>
<script>
$('#flip').bind('click', function() {
var x = document.getElementById("flip").name;
if (x == 'Flip')
{
$(this).text('Flop');
}
else
{
$(this).text('Flip');
}
});
</script>
</body>
</html>
I'm trying to change the button each time it is clicked , but it doesn't work .
Any idea how to fix it ?
Much appreciated
There is no name attribute on your <button>, so you'll always get empty value. No need for document.getElementById because button is in this. Simply call text() without parameters to get current value:
var x = $(this).text();
Update
Here is demo in JsFiddler.
I would do something like this:
HTML:
<button id="flipflop">flip</button>
javascript:
var flip = true;
$("#flipflop").click(function(){
if(flip)
$("#flipflop").text("flop");
else
$("#flipflop").text("flip");
flip = !flip;
})
FIDDLE
edit: if you want to be really savvy, I would use the following line:
var flip = ($("#flipflop").text() === "flip");
Which automatically determines which way you need to flip (or is it flop?).

trouble with if statement going to button and div

I'm trying to get my function to look at a number entered into a text box, and if it's larger than x number (I put in 5 for example purposes) display one message in theDiv, if less than or equal to, another. Right now I click the button and nothing happens. I'm trying to learn Javascript for the first time, so forgive my ignorance - where did I go wrong? Thank you!!
<script>
function function1()
{
for (var theNumber)
{
var theNumber=parseFloat(document.getElementById('theInput').value);
if (theNumber < 5)
{
document.getElementById('theDiv').innerHTML="Smaller.";
}
else (theNumber >= 5)
{
document.getElementById('theDiv').innerHTML="Larger.";
}
}
</script>
<body>
<input type="button" id="theButton" value="click me!" onclick="function1()"></p>
<div id="theDiv"></div>
</body>
</html>
change this
var theNumber=parseFloat(document.getElementById('theInput').value);
to
var theNumber=parseFloat(document.getElementById('theButton').value);
and dont use any condition in else, else do not take any condition, rather than that you can use else if
First of all, you are missing a closing curly bracket.
And then your else part should not have any conditions.
Your for syntax is wrong and you dont need it here.
Last but not the least, you are getting the value of theInput, that is not there in the form at all.
So your modified code looks like this
function function1() {
var theNumber = parseFloat(document.getElementById('theInput').value);
if (theNumber < 5) {
document.getElementById('theDiv').innerHTML = "Smaller.";
} else {
document.getElementById('theDiv').innerHTML = "Larger.";
}
}
Working example: http://jsfiddle.net/V3QBc/
There are several problems present here.
1.) You do not have a DOM element with an id="theInput"
2.) You are mis-using the for construct, which is for looping. The correct syntax is for (incrementer_variable; condition_to_continue_looping; increment_by) {}
3.) You are specifying an else if condition using only else (meaning your condition will be ignored.
4.) You are missing a closing curly brace (}) to finish defining function1.
To fix these, add a DOM element with id="theInput", remove the for (it's not needed here), add that last curly brace, and either add an if after the else or remove the condition (depending on the behavior you want).
<input type="text" id="theInput">
<input type="button" id="theButton" value="click me!" onclick="function1()">
<div id="theDiv"></div>
and the JavaScript:
function function1() {
var theNumber = parseFloat(document.getElementById('theInput').value, 10);
if (theNumber < 5) {
document.getElementById('theDiv').innerHTML = "Smaller.";
} else if (theNumber >= 5) {
document.getElementById('theDiv').innerHTML = "Larger.";
}
}
Another minor problem (in potentia) is that you are not specifying a radix for parseFloat. This can cause problems if the JavaScript engine thinks your number has a different base than 10. To ensure you always get a base10 number, specify a radix for the second argument to parseFloat: (var x = parseFloat(otherVar, 10);).
Demo: http://jsfiddle.net/8tS7t/

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

Im having an issue with displaying javascript output without any user action

this is the Question: An integer is said to be prime if it is greater than 1 and divisible only by 1 and itself. For example, 2, 3, 5 and 7 are prime, but 4, 6, 8 and 9 are not.
a) Write a function that determines whether a number is prime.
b) Use this function in a script that determines and prints all the prime numbers between 1 and 10000.
How many of these 10000 numbers do you really have to test before being sure that you have found all the primes? Display the results in a <textrarea>.
This is my code:
function isPrime(n)
{
boolean prime=true;
if(n==1 || n==0)
{
prime= false;
}
if(n==2)
{
prime= true;
}
else
{
for(int i=2;i<n;i++)
{
if(n%i==0)
{
prime= false;
}
}
}
return prime;
}
function printPrimes()
{
document.writeln("<textarea rows="10" cols="15">");
for(var i=0; i<=1000; i++)
{
if(isPrime(i)==true)
{
document.writeln("<p>" + i + "</p>");
}
}
document.writeln("</textarea>");
}
printPrimes();
This is My html:
<!DOCTYPE html>
<html>
<head>
<script src="prime.js" type="text/javascript"> </script>
</head>
<body>
<h1> Prime numbers between 1 and 1000 are: </h1>
</body>
When i open the html file on chrome only the header shows up the script doesnt seem to run!
You're importing the script in the <head>, so that's where it's output will go. Try moving it to the <body>.
That's possibly the slowest way to find primes.
edit — another problem is this:
for(int i=2;i<n;i++)
There is no int keyword in JavaScript - it's var. That would cause a syntax error, which would show up in the error console. Neither is there a boolean keyword (declaration of "prime"). It's important to keep the error console open while doing any HTML/JavaScript development.
This is because you are attempting to write the <textarea> to the <head> element. Try loading/executing your script within the <body>.

Categories