Reputation: 195
I have a project on jsFiddle in which I want to link a button to the following Javascript code:
var computerChoice = math.random();
if (computerChoice < 0,5) {
console.log("you lost")
} else {
console.log("you've won"
}
So if I press the button, a random number should be generated leading to one of the two responses. How can I get this working?
Upvotes: 0
Views: 103
Reputation: 1578
This might help you:
<Br>
doesnt need to be closeduser181796 have a nice rest of day!
$('#Start').click(function(){
number = Math.random();
number = number.toFixed(1);
if (number < 0.5) {
console.log("you lost " + number);
} else {
console.log("you win " + number);
}
});
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<span> text box 1 </span>
<input class = "styleYellow" type = "text"> </input>
<br> <br>
<span> text box 1 </span><input type = "text"> </input>
<br> </br>
<button id="Start">Ga naar pagina 1</button>
<button id="I_dont_know">Ga naar pagina 2</button>
Upvotes: 0
Reputation: 1453
Pass your function name in onclick
event of your button
<button onclick="randomFunction();">click to call function randomFunction</button>
Script
function randomFunction() {
//here should be your code
}
Upvotes: 0
Reputation: 16184
function tosser(){
if (Math.random() < 0.5) {
return "you lost";
} else {
return "you\'ve won";
}
}
$("button").on("click",function(){
alert(tosser());
});
Upvotes: 1
Reputation: 11777
I have a question about jquery.
I'm assuming you can use jQuery then. Call the function on the click event:
function randomNumber(){
var computerChoice = Math.random();
if (computerChoice < 0.5) {
console.log("you lost")
} else {
console.log("you've won");
}
}
$("button").click(randomNumber);
Or:
var button = document.getElementById("button");
button.onclick = function(){
randomNumber();
}
Also, you need to capitalize the m
in Math
.
Upvotes: 0
Reputation: 40671
$('#yourButton').click(function(){
// insert your JS here
})
To elaborate...the above is attaching a click event listener to your button. This is the very essence of jQuery: select an item from the DOM, attach logic to it. The above assumes you gave your button an id
of 'yourButton' but you could select the button in any number of ways using jQuery selectors (google that to find plenty of tutorials).
Upvotes: 1