首页 > 解决方案 > 有没有办法接受用户输入并将其转换为 JS 的变量?

问题描述

我目前有一个网页,我希望用户能够输入他们的姓名和年龄。完成后,他们点击提交,第一个输入设置为 var name,第二个输入框设置为 var age。这可能吗?

这是我尝试过的

<form>
    <input type="text" Name:"firstname"><br>
    <input type="text" Age:"age"><br>
    <input type="submit" value="Done">
</form>

但是,我不确定如何将输入设置为值。

标签: javascripthtmlforms

解决方案


首先 - 您的 HTML 标记不正确。我真诚地建议您阅读此内容。

https://www.w3schools.com/html/default.asphttps://www.w3schools.com/js/default.asp 或您选择的任何其他网站。

其次 - 一旦你更正了你的标记 - 你可以这样做:

<input type="text" id="firstname">
<input type="text" id="age">
<input type="button" id="submit" value="Set The Variables">

<script>
//Get the dom element you want to listen to and attach a click event
document.getElementById("submit").addEventListener("click", setVars); 


function setVars(){
//Set the variables
var firstname = document.getElementById("firstname").value;
alert ("Vars Set :" + firstname);
}
</script>

推荐阅读