Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript not getting value of input box

I seem to be having trouble with passing the value of an input box to anything else in my javascript. It's not producing any errors - and I remember reading somewhere that you can have issues if the document hasn't finished loading - but I'm pretty sure it has!

The code in question is as follows in the javascript:

var address = getElementById(addyInput).value;
document.getElementById('add').innerHTML = address;

And in the HTML

<form>
<input name="addyInput" placeholder="Don't forget postcode!">
</form>

<button id="start" onclick="initialize()">Start!</button>

<p>Address Test
<div id="add"></div>
</p>

I know that the button itself is working as it fires the rest of my code fine without the offending code - however the moment I uncomment that little block at the top, it just does nothing. (no errors etc)

Any help on that one would be hot! Thanks :)

Update:

I now have it working! Thanks muchly for all the help!!

like image 268
AltheFuzz Avatar asked Jul 13 '26 09:07

AltheFuzz


1 Answers

Your form needs to look like this (add an id attribute):

<form>
<input id="addyInput" name="addyInput" placeholder="Don't forget postcode!">
</form>

And the first line of Javascript needs to look like this (since getElementById is expecting an ID rather than a name).

var address = getElementById('addyInput').value;

Additionally, getElementById expects the id argument to be a string (hence the quotes). If you pass it addyInput without quotes, it'll try to interpret addyInput as a variable which has a value of undefined and you won't get back the DOM element you want.


Or, if you were using jQuery, you could leave the form markup as-is and change the Javascript to this:

var address = $('input[name=addyInput]').val();
like image 186
Mark Biek Avatar answered Jul 15 '26 21:07

Mark Biek