javascript - 与 HTML 和 Javascript 相关的数组问题

标签 javascript html

我有这段简单的代码。当用户选择“其他”时,会出现 <input type=text>应该会出现。

但它仅在仅选择一个值时有效。

用户可以在同一个select中随机添加类型,因此代码无法更改。据我所知,在javascript中需要使用 foreach .

所以我的问题是,如何让每个<input type=text>出现在 select 的每个中元素而不是只出现在第一个元素中。

function Pack(val){
 var element=document.getElementById('otherpack');  
 if(val=='others')
   element.style.display='block';
 else  
   element.style.display='none';
} 
<select name="Type[]" onchange='Pack(this.value);' required>
<option value="Orange">Orange</option> 
<option value="Apple">Apple</option>    
<option value="others">Others</option>                          
<input type="text" name="othermethod[]" id="otherpack" style="display:none"/>
</select>

<select name="Type[]" onchange='Pack(this.value);' required>
<option value="Orange">Orange</option> 
<option value="Apple">Apple</option>    
<option value="others">Others</option>                          
<input type="text" name="othermethod[]" id="otherpack" style="display:none"/>
</select>

<select name="Type[]" onchange='Pack(this.value);' required>
<option value="Orange">Orange</option> 
<option value="Apple">Apple</option>    
<option value="others">Others</option>                          
<input type="text" name="othermethod[]" id="otherpack" style="display:none"/>
</select>

最佳答案

Here我的解决方案是:

function Pack(v) {
  var inputBox=v.nextSibling;
 var selectedValue=v.options[v.selectedIndex].value;
 if (selectedValue=="others") {
    inputBox.style.display='block';
 } else {
    inputBox.style.display='none';
 }
}

这应该是最稳定的解决方案。

关于javascript - 与 HTML 和 Javascript 相关的数组问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60164089/

相关文章:

javascript - 另一个 "toggle visibility"问题

javascript - 从 ironRequest promise 中检索状态代码

php - 如何显示数据库中的最后五行

javascript - 将变量添加到 img 标签

javascript - Reactjs 中的嵌套循环返回简单的 ListItem - -Object.values 和 Object.keys

html - 使用 Twitter Bootstrap 连续 4 列

php - 使用 php 将我的 sql 数据库上传到我的 html 表单中

javascript - 如何重置 UWP WebView 的内容缩放因子

html - html5页面的对齐方式

javascript - 如何解决 JavaScript 错误 : method XX is undefined?