1

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

function randomNum(result, oneToHundred, randomNum) {
    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.

3
  • You are missing "()" in onclick="alert(randomNum)" it should be onclick="alert(randomNum())" Commented Jul 20, 2022 at 9:05
  • For your next project, you might want to move from HTML's 'on...' properties (eg <button id="my-btn" onClick="myFunction()"></button>) to JS's .addEventListener() method (eg <button id="my-btn"></button> <script>let myBtn = document.getElementById("my-btn"); myBtn.addEventListener("click", myFunction)</script> ). MDN likes this way bc it lets you add many listeners, gives finer control of listener timing, and works on any event target -- plus it keeps JS out of HTML. (I can write a better example if you like.) Commented Jul 20, 2022 at 10:00
  • If you could provide an example (preferably something even a brick wall would understand) that would be very much appreciated Commented Jul 20, 2022 at 19:25

1 Answer 1

1

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));
}
Sign up to request clarification or add additional context in comments.

1 Comment

So, if i understand it correctly, i was calling to alert for something that couldn't be? (I dunno if i'm getting it across correctly but i think i understand what i did wrong) Anyways it's working now and thanks for your help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.