Click here to Skip to main content
15,889,216 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
I've been sitting and writing this code for about 4 hours and I still can't get it work
can someone help me please?
this is the html code:
<!DOCTYPE html>
<html>
<head>
  <link rel='stylesheet' type='text/css' href='style.css'>
</head>
<body>
<button id = "button">test</button>
<h1 style = "font-size: 1.5em; font-family: verdana; color: black;">the answer</h1>
<script src='https://code.jquery.com/jquery-3.1.0.min.js'></script>
<script type="text/javascript">
$('#button').on('click', function() {
	var randomAnswer = Math.random();
	if(randomAnswer < 0.1) {
alert("hey");
	} else if(randomAnswer <= 0.2) {
alert("hey");
	} else if(randomAnswer <= 0.3) {
alert("hey");
	} else if(randomAnswer <= 0.4) {
alert("hey");
	} else if(randomAnswer <= 0.5) {
alert("hey");
	} else if(randomAnswer <= 0.6) {
alert("hey");
	} else if(randomAnswer <= 0.7) {
alert("hey");
	} else if(randomAnswer <= 0.8) {
alert("hey");
	} else if(randomAnswer <= 0.9) {
alert("hey");
	} else {
alert("hey");
	}
});
$(document).ready(main);
</script>
</body>
</html>

I added the alert("hey"); just to see if it works and I don't know why but the jquery doesn't interact with the html.

What I have tried:

I went to a lot of guides and tutorial and to w3schools and still didn't find how to fix it
Posted
Updated 3-Mar-17 11:31am

1 solution

It boils down to the very basic of jQuery, the Selectors. Do you understand the relation between:
<button id = "button">
and
$('#button')
? If not, head over to jQuery Selectors[^]. Once you learn how the jQuery selector work, apply it to your code. Let say you want the answer to be displayed in the h1 tag,
HTML
<button id = "button">test</button>
<h1 id="answer">the answer</h1>
<script src='https://code.jquery.com/jquery-3.1.0.min.js'></script>
<script>
$('#button').on('click', function() {
    var $answer = $("#answer");
	var randomAnswer = Math.random();
    $answer.text(randomAnswer);
});
</script>
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900