HTML使用没有数据库或php的<form>获取输入[重复]
Posted
技术标签:
【中文标题】HTML使用没有数据库或php的<form>获取输入[重复]【英文标题】:HTML getting input using <form> without database or php [duplicate] 【发布时间】:2020-09-29 10:29:50 【问题描述】:我正在使用 html、css 和 javascript 在网络浏览器中创建游戏。我问用户他/她想要多少个对手,使用无线电输入和一个按钮来提交。我没有任何地方可以使用表单操作存储数据。我只是希望我的 javascript 可以访问它。是否可以不使用表单或不将输入存储在任何地方的数据库中?这是html:
<form id="database">
<label for="players1">
<input id="players1" type="radio" value=1 name="playerAmount">1
</label>
<label for="players2">
<input id="players2" type="radio" value=2 name="playerAmount">2
</label>
<label for="players3">
<input id="players3" type="radio" value=3 name="playerAmount">3
</label>
<label for="players4">
<input id="players4" type="radio" value=4 name="playerAmount">4
</label>
<label for="players5">
<input id="players5" type="radio" value=5 name="playerAmount">5
</label>
<button type="submit">Done</button>
</form>
这是我试图获得响应但它不起作用(javascript)
var players;
players = document.getElementById("database").playerAmount;
document.write(players);
控制台显示:Uncaught TypeError: Cannot read property 'playerAmount' of null
at poker.js:2
但 playerAmount 在 URL 中更新为输入的金额
【问题讨论】:
【参考方案1】:使用querySelector
直接获取选中单选按钮的值。
document.querySelector('button#submit').addEventListener('click', function()
var players = document.querySelector('input[name="playerAmount"]:checked').value;
document.write(players);
);
<form id="database">
<label for="players1">
<input id="players1" type="radio" value=1 name="playerAmount">1
</label>
<label for="players2">
<input id="players2" type="radio" value=2 name="playerAmount">2
</label>
<label for="players3">
<input id="players3" type="radio" value=3 name="playerAmount">3
</label>
<label for="players4">
<input id="players4" type="radio" value=4 name="playerAmount">4
</label>
<label for="players5">
<input id="players5" type="radio" value=5 name="playerAmount">5
</label>
<button type="submit" id="submit">Done</button>
</form>
【讨论】:
【参考方案2】:从表单元素的“playerAmount”中取值,你就差不多完成了。
document.getElementById('done').addEventListener('click', function(e)
e.preventDefault();
var players;
players = document.getElementById("database").playerAmount.value;
console.log(players);
)
<form id="database">
<label for="players1">
<input id="players1" type="radio" value=1 name="playerAmount">1
</label>
<label for="players2">
<input id="players2" type="radio" value=2 name="playerAmount">2
</label>
<label for="players3">
<input id="players3" type="radio" value=3 name="playerAmount">3
</label>
<label for="players4">
<input id="players4" type="radio" value=4 name="playerAmount">4
</label>
<label for="players5">
<input id="players5" type="radio" value=5 name="playerAmount">5
</label>
<button type="submit" id="done">Done</button>
</form>
【讨论】:
以上是关于HTML使用没有数据库或php的<form>获取输入[重复]的主要内容,如果未能解决你的问题,请参考以下文章