Javascript使用选择元素创建输入字段 [英] Javascript create input field using a select element
问题描述
我正在尝试创建一个计算纸牌游戏得分的简单网站.该网站将提示用户输入玩家人数,并返回该人数字段以输入姓名.
I am trying to create a simple website that calculates a card game score. The website will prompt a user to enter the number of players and return that number of fields for name inputs.
但是,按照我目前的代码显示,当用户输入玩家人数时,该网站可能只显示一个字段一秒钟,然后消失.我希望有人(新手程序员)可以帮助我如何使用Javascript动态创建输入文本字段.谢谢!
However, as my code stands currently, when a user enters the number of players, the website only shows one field for maybe a second and disappears. I was hoping that someone could help me (a novice programmer) on how to create input text fields dynamically with Javascript. Thanks!
//*****script.js*****
let response = parseInt(document.getElementById("players").value);
const playerNames = () => {
let player;
for (let i = 0; i < response; i++) {
player = document.createElement('input');
player.type = 'text';
document.body.appendChild(player);
};
}
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
</head>
<body>
<form class="start" action="index.html" method="post">
<p>How many players?</p>
<select id="players" class="" name="">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<input type="submit" value="Submit" onclick="playerNames()"/>
</form>
<script src="script.js"></script>
</body>
</html>
推荐答案
您无需将字段包装在< form>
中.如果您这样做,则由于您的按钮是提交类型:默认情况下,您的浏览器将尝试将表单提交到另一页&重定向.您可以简单地将< div>
用作包装器.完成此操作后,您可以删除HTML属性 action
&方法
,因为这些属性对于代码库不再是必需的,因为您不再提交表单.
You need not wrap your fields in a <form>
. If you do this, since your button is type of submit: by default your browser will attempt to submit the form to another page & redirect. You can simply use <div>
as a wrapper. Once you do this, you can remove the HTML attributes action
& method
since these attributes are no longer essential to your code base as you are no longer submitting a form.
对于脚本,只需将输入的收集移到函数内部而不是外部.因此onclick事件,即您从< select>
As for the script, simply move the gathering of the input inside of the function not outside. So onclick event, that is the time you get the input from the <select>
<body>
<div class="start">
<p>How many players?</p>
<select id="players" class="" name="">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<button onclick="playerNames()">Submit</button>
</div>
<script>
//*****script.js*****
const playerNames = () => {
let response = parseInt(document.getElementById("players").value);
let player;
for (let i = 0; i < response; i++) {
player = document.createElement('input');
player.type = 'text';
document.body.appendChild(player);
};
}
</script>
</body>
这篇关于Javascript使用选择元素创建输入字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!