Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery/JavaScript not working inside script tags [closed]

I want, my HTML document to output random numbers for Dungeons and Dragons. However, the code isn't working and I can't workout why.

<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.10.2.js">
$(document).ready(function(){
  $("#d4").click(function(){
    var out = Math.random(1,4);
    alert(out);
  };
});
</script>
</head>
<body>
  <p id ="d4">Roll a d4</p>
</body>
</html>
like image 750
Ross Hudson Avatar asked Aug 15 '26 10:08

Ross Hudson


2 Answers

The script tag cannot have the src attribute and a body, you need to use separate script tags

<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(document).ready(function () {
    $("#d4").click(function () {
        var out = Math.random(1, 4);
        alert(out);
    }); //missing ) here
});
</script>

Script src

This attribute specifies the URI of an external script; this can be used as an alternative to embedding a script directly within a document. script elements with an src attribute specified should not have a script embedded within its tags.

like image 177
Arun P Johny Avatar answered Aug 16 '26 23:08

Arun P Johny


After alert you need to close the parenthesis to the click function.

$(document).ready(function(){
    $("#d4").click(function(){
        var out = Math.random(1,4);
        alert(out);
    }); // <-- here
});
like image 43
VtoCorleone Avatar answered Aug 16 '26 23:08

VtoCorleone



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!