Weber Weber - 1 month ago 6
Javascript Question

How would I activate my script on button click only?

So my HTML is:

<!DOCTYPE>
<head>
<script src="js/problem1.js"></script>
</head>
<body>
<input id="clickMe" type="button" value="Problem #1" onclick="problem1();" />
<script src="js/problem1.js"></script>
</body>


The script I am trying to run is:

var counter = 0
var total = 0
var start = prompt("Enter a number here to find the sum of all numbers that are:\n-Between 0 and your number\n-Divisible by 3 or 5")

function problem1(start) {
for (counter = 0; counter < start; counter++) {
if (counter < start) {
if (counter % 3 == 0) {
total += counter;
}
else if (counter % 5 == 0) {
total += counter;
}
}
else if (counter == start) {
if (counter % 3 == 0) {
total += counter;
alert(total);
}
else if (counter % 5 == 0) {
total += counter;
alert(total);
}
else {
alert(total);
}
}
}
}


The problem I am running into is that right now the script runs on page load and instantly gives me a prompt for creating the
start
variable. After entering an integer and clicking
Ok
the prompt window disappears and nothing happens. I do realize that the script is running on its own because it is called in the
<head>
. Problem is I don't know how else to call it, like on button click. I don't want to use JQuery. I have seen lots of answers like this one but I am looking for something that doesn't require JQuery. How would I accomplish this?

UPDATE

Thank you for the help. Now I have stumbled upon a second problem. I can't get the script to run or display the alert (not sure which)

Answer

put your prompt inside the problem function

function problem1() {
    var counter = 0   
    var total = 0    
    var start = prompt("Enter a number here to find the sum of all numbers that are:\n-Between 0 and your number\n-Divisible by 3 or 5")

    for (counter = 0; counter < start; counter++) {   
        if (counter < start) { 
            if (counter % 3 == 0) {
                total += counter;
                alert(total);
            }
            else if (counter % 5 == 0) {
                total += counter;
                alert(total);
            }

        }
        else if (counter == start) {
            if (counter % 3 == 0) {
                total += counter;
                alert(total);
            }
            else if (counter % 5 == 0) {
                total += counter;
                alert(total);
            }
            else {
                alert(total);
            }
        }
    }
}
<!DOCTYPE> 
<head>
    <script src="js/problem1.js"></script>
</head> 
<body> 
    <input id="clickMe" type="button" value="Problem #1" onclick="problem1();" />
    <script src="js/problem1.js"></script>
</body>