-4

So I've been working in html/javascript for the first time and I need to get user input through boxes/buttons and use that data to call a function, something like this:

<input id="xstart" type="number" min="0" max = "100"/>
<input id="ystart" type="number" min="0" max = "100"/>
<input id="zstart" type="number" min="0" max = "100"/>
<input id="clickit" type="button" value="click" onclick="myfunc(xstart, ystart, zstart);" />

function myfunc(num0, num1, num2) { do things with it }

I cannot figure out how to get this to work, it does seem to call myfunc but it crashes because the values in xstart, ystart and zstart are not actually numbers, I think they are strings but I am not sure.

Any help or links to tutorials on things like this for a first time programmer would be helpful. Thank you.

Dilanlius
  • 7
  • 4
  • 1
    We aren't here to point you to documentation, we're here to help with specific programming issues. Please read the FAQs! – Sterling Archer Mar 02 '15 at 19:24
  • Pop open the console, you'll see some errors. You can't just add the ID of the input you want to pass like that, it'll error, the compiler thinks you're passing variables `xstart`, `ystart`, `zstart` – tymeJV Mar 02 '15 at 19:27

1 Answers1

3

First, I would recommend you separate your HTML from your JS, for easier debugging and more freedom.

You can bind myFunc to #clickit in your JS like so:

document.getElementById('clickit').addEventListener('click', myFunc);

Then get the values in myFunc and use them. parseInt will convert them to numbers. Here is the full code:

var xInput = document.getElementById('xstart'),
    yInput = document.getElementById('ystart'),
    zInput = document.getElementById('zstart');

document.getElementById('clickit').addEventListener('click', myFunc);

function myFunc(){
    var xstart = parseInt( xInput.value ),
        ystart = parseInt( yInput.value ),
        zstart = parseInt( zInput.value );
    alert( xstart + ', ' + ystart + ', ' + zstart);
}

JS Fiddle Demo

Community
  • 1
  • 1
blex
  • 24,941
  • 5
  • 39
  • 72