简体   繁体   English

HTML 表单转换为 Javascript 变量

[英]HTML Form into Javascript Variable

I'm reasonably new to Javascript so sorry if this has a simple answer.如果这有一个简单的答案,我对 Javascript 相当陌生,所以很抱歉。

I would like to make the name that a user inputs in a form into a javascript variable.我想将用户在表单中输入的名称输入到 javascript 变量中。 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'.例如,如果用户在表单中输入名称“James”,我希望变量“ans1”等于字符串“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');更改var ans1 = document.getElementById.value('username'); . .

To : var ans1 = document.getElementById("username").value;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.并且始终将您的 alert() 放在函数的开头。 if you want to test function-hit :)如果你想测试功能命中:)

Just replace below line只需替换下面的行

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

with

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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