javascript - 在输入文本javascript中输入数字时如何显示选项

标签 javascript html web

很抱歉,我是 javascript 新手,所以我想问一些问题。所以我想当我在输入文本中键入数字时突然出现一个选项。例如,如果我在输入文本中键入 2,则会出现 2 个选项。

    <input type="num" name="member" id="member" value="">

最佳答案

我认为这可以为您指出正确的方向:

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>

与我的编辑相关的注释:

正如我的答案中的评论所述,如果用户更改输入值,将会出现不需要的行为。例如用户输入 2,但将其更改为 4。之后,用户将有 6 个选择,而他们只想有 4 个。

因此,我在脚本中添加了 document.getElementById('selects').innerHTML = ""; 以防止出现这种情况。为此,我还更改了脚本以将选择附加到 div,而不是直接附加到正文。

关于javascript - 在输入文本javascript中输入数字时如何显示选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50385267/

相关文章:

javascript - 是否可以在不重复所述值的情况下从三元运算返回比较值+字符串?

java - Web 应用程序关闭后 ScheduledThreadPoolExecutor 不会终止

html - 反转 CSS 属性以更改为 RTL

javascript - 有没有办法在 JS 函数类中使用属​​性获取和设置符号?

javascript - 如何在同一个元素上设置多个属性

javascript - 如何在数据表中添加编辑和删除按钮

javascript - Applescript,单击带有 do JavaScript 的复选框

javascript - 移相器 : Change anchor from Body?

javascript - 隐藏另一个 div 之后的 div

html - 将 ng-repeat 中的 bootstrap nav (ul)-width 自动调整为 container-width