Reputation: 57
I would like the JQuery method, .html
, to put <img src='file.png'>
in a <td>
based on the value generated by the Math.random()
function. The if/else statements are used to determine the td
in which <img src='file.png'>
is added.
The problem is that, whenever I reload the page, <img src='file.png'>
is always added to #bottom-right
no matter what value is generated by Math.random
.
Here's my code:
// script.js
$(document).ready(function () {
var value = Math.random;
if (value <= 0.1) {
$("#top-left").html("<img src='file.png'>");
} else if (value <= 0.2 && value > 0.1) {
$("#top-middle").html("<img src='file.png'>");
} else if (value <= 0.3 && value > 0.2) {
$("#top-right").html("<img src='file.png'>");
} else if (value <= 0.4 && value > 0.3) {
$("#middle-left").html("<img src='file.png'>");
} else if (value <= 0.5 && value > 0.4) {
$("#middle-middle").html("<img src='file.png'>");
} else if (value <= 0.6 && value > 0.5) {
$("#middle-right").html("<img src='file.png'>");
} else if (value <= 0.7 && value > 0.6) {
$("#bottom-left").html("<img src='file.png'>");
} else if (value <= 0.8 && value > 0.7) {
$("#bottom-middle").html("<img src='file.png'>");
} else {
$("#bottom-right").html("<img src='file.png'>");
}
});
<!-- page.html -->
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<table border="1px">
<tr>
<td class="square" id="top-left"></td>
<td class="square" id="top-middle"></td>
<td class="square" id="top-right"></td>
</tr>
<tr>
<td class="square" id="middle-left"></td>
<td class="square" id="middle-middle"></td>
<td class="square" id="middle-right"></td>
</tr>
<tr>
<td class="square" id="bottom-left"></td>
<td class="square" id="bottom-middle"></td>
<td class="square" id="bottom-right"></td>
</tr>
</table>
</body>
</html>
Any help shall be appreciated.
Upvotes: 0
Views: 45
Reputation: 6042
You also may need to round down the number to a single decimal place
Upvotes: -1
Reputation: 4021
instead of
Math.random
change it to
Math.random()
otherwise value is just a function reference, which will always hit your else statement
Upvotes: 1