EdwardBlack EdwardBlack - 3 months ago 12
Javascript Question

Generate numbers and write them to the clipboard

I want to let the user input a min and a max value, then i try to generate the numbers from min to max and save the result into the clipboard.

However, i always get

Uncaught ReferenceError: generateNumbers is not defined
and can't explain why.



window.onLoad = function()
{
function generateNumbers()
{
var min = document.getElementById("min").value;
var max = document.getElementById("max").value;
var result = "";

for(var i=min; i < max; i++ )
{
result = result + i + ";";
}
copyToClipboard(result);
console.log(result);
}

function copyToClipboard(text)
{
window.prompt("Copy to clipboard: Ctrl+C, Enter", text);
}
}

<label>MIN: </label><input type="text" id="min"/><br>
<label>MAX: </label><input type="text" id="max"/><br>
<button onclick="generateNumbers">send</button>





JSFIDDLE: https://jsfiddle.net/n303o8tz/1/

SOLVED JSFIDDLE: https://jsfiddle.net/n303o8tz/4/

Answer

You need to remove that window.onload part and simply call the function in your button's onclick handler.

Here's one way of doing it:

<meta charset="UTF-8">
<script>
function generateNumbers() {
    var min = parseInt(document.getElementById("min").value);
    var max = parseInt(document.getElementById("max").value);
    var result = "";
    for (var i = min; i <= max; i++) {
        result += i;
        if (i < max) {
            result += ";";
        }
    }

    console.log(result);
    copyToClipboard(result);
}

function copyToClipboard(text) {
    window.prompt("Copy to clipboard: Ctrl+C, Enter", text);
}
</script>
<input id="min" type="text" value="1">
<input id="max" type="text" value="10">
<button onclick="generateNumbers()">Test</button>