简体   繁体   中英

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!!

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();

Make sure to specify and id on the input. You only have a name .

您需要将id“addyInput”添加到表单输入而不仅仅是名称。

getElementById expects a string.

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

If you put this directly into a script section in the head, then you will have a problem because the page is not loaded completely but the code is executed already.

And of course you should define an id for the input element as the others already said.

what you are getting is an array, you need to fetch your array into some readable data. Try something like:

  • $value = array_shift( $yourarray );

or if it's a multi value array you can just loop it to fetch out the values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM