Home > Software engineering >  Embedding scripts in html buttons
Embedding scripts in html buttons

Time:07-20

So, I'm a beginner programmer and figured I could do something short and fun. I made a short program in like 5 minutes, but I ran into a problem where I can't figure out, how to make a button that runs a said script when pressed (e.g. makes an alert with a random number in it) Here's my code

<!DOCTYPE html>
<html>
    <Head>
        <h2>
        Random number Generator
        </h2>
    </Head>
    <body>
         <script src ="Script.js"></script>
        <button type="button" onclick="alert(randomNum)"> Generate! </button>
    </body>
</html>

and the script part here

    let newNumber = Math.random()
    let oneToHundred = newNumber * 1000
    let result = Math.floor(oneToHundred)
    return result
};
alert(randomNum) ```

I just can't figure out how to make the button search for a script and run it when pressed. I tried to embed the script search to the onclick part, but i got a syntax error.
Any help appreciated
Seven

CodePudding user response:

This would be simple example.

HTML file.

<!DOCTYPE html>
<html>
    <Head>
        <h2>
        Random number Generator
        </h2>
    </Head>
    <body>
         <script src ="Script.js"></script>
        <button type="button" onclick="showMessage()"> Generate! </button>
    </body>
</html>

JavaScript file.

function showMessage() {
    alert("Hello friends, this is random number: "   Math.floor(Math.random() * 11));
}
  • Related