简体   繁体   中英

HTML Form into Javascript Variable

I'm reasonably new to Javascript so sorry if this has a simple answer.

I would like to make the name that a user inputs in a form into a javascript variable. For example, If the user inputs the name 'James' into the form, I would like the variable 'ans1' to be equal to the string 'James'. Heres my code...

 <form> Name: <input type="text" id="username" /> <input type="submit" value="Submit" onClick="makeans1()" /> </form> <script> function makeans1() { var ans1 = document.getElementById.value('username'); alert(ans1); } </script>

The reason I have added an alert is to check to see if the code has worked. Any help would be very much appreciated. Thanks

Change : var ans1 = document.getElementById.value('username'); .

To : var ans1 = document.getElementById("username").value; .

 function makeans1() { var ans1 = document.getElementById("username").value; alert(ans1); }
 <form> Name: <input type="text" id="username" /> <input type="submit" value="Submit" onClick="makeans1()" /> </form>

The correct code should be:

var ans1 = document.getElementById('username').value;

And always put your alert() 's at the beginning of the function. if you want to test function-hit :)

Just replace below line

var ans1 = document.getElementById.value('username');

with

var ans1 = document.getElementById('username').value

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