我很抱歉,但我是javascript的新手,所以我想问一些问题。因此,当我在输入文本中键入num时,我想突然出现一个选项。因此,例如,如果我在输入文本中键入2,则会出现2个选项。
<input type="num" name="member" id="member" value="">
答案 0 :(得分:2)
我认为你可以指出正确的方向:
function addOptions() {
// "Reset" the div to prevent unwanted behavior
document.getElementById('selects').innerHTML = "";
// Get the value of your input field
var inputValue = document.getElementById('member').value;
// A loop to append as many selects as required (e. g. if inputValue is 2, 2 selects will appear
for (var i = 0; i < inputValue; i++) {
var select = document.createElement('select'); // Create the select
var option = document.createElement('option'); // Create the option for the select
option.innerText = "Example"; // Set a text for the option
select.appendChild(option); // Append the option to the select
document.getElementById('selects').appendChild(select); // Append the select to the body
}
}
<input type="number" onkeyup="addOptions()" name="member" id="member" value="">
<div id="selects"></div>
与我的编辑相关的注释:
正如我的回答所述,如果用户更改输入值,则会出现不需要的行为。 E. g。用户输入2,但将其更改为4.之后,当用户只想拥有4时,用户将有6个选择。
因此,我在脚本中添加了document.getElementById('selects').innerHTML = "";
以防止这种情况发生。为此,我还更改了脚本以将选择附加到div,而不是直接附加到正文。
答案 1 :(得分:1)
以下是使用javascript进行操作的方法。另外,我假设您需要在下次更改之前清除选项。
function createOptions(iterations){
var select = document.getElementById("optmem"); //assuming select will be already present
removeOptions(select); //clear options
for(var i=0;i!= iterations;i++){
//loop through each iterations
var option = document.createElement("option");
option.text = "Text "+i;
option.value = "myvalue "+i;
select.appendChild(option); //append it to select
}
}
function removeOptions(selectbox)
{
var i;
for(i = selectbox.options.length - 1 ; i >= 0 ; i--)
{
selectbox.remove(i);
}
}
<input type="num" name="member" id="member" onchange="createOptions(this.value)" value=""/>
<select id="optmem">
</select>