如果在多选输入中选择了 'Other',Javascript 显示/隐藏文本字段输入

标签 javascript jquery forms multiple-select

恐怕我陷入了困境,我希望得到一些社区智慧。

我正在构建一个 HTML 表单,它将数据提交到 SQL 数据库。表单字段之一是多选输入字段,用户可以在其中选择正在执行的操作类型。然后,该数组以逗号分隔值的形式导出到 SQL 字段。

我遇到的问题是,我还希望用户能够输入自定义操作类型(如果该类型未包含在提供的列表中)。理想情况下,这将涉及在多重选择中选择“其他”并显示一个新的文本输入字段。

到目前为止,我只能在用户选择“其他”而没有选择其他内容时才显示文本输入字段。如果用户选择了多个项目(其中之一是“其他”),我可以显示该字段吗?

非常感谢

function showfield(episode_procedure){
          if(episode_procedure=='Other')document.getElementById('otherprocedure').innerHTML='Other: <input type="text" name="episode_otherprocedure" style="width: 450px;"/>';
          else document.getElementById('otherprocedure').innerHTML='';
        }
   
<select multiple="multiple" data-placeholder="Click to select..." size="7" name="episode_procedure[]" style="width: 450px;" onchange="showfield(this.options[this.selectedIndex].value)"></p>
        <option value="anterior resection">anterior resection</option>
        <option value="appendicectomy">appendicectomy</option>
        <option value="Other">Other</option></select>
        
        <div id="otherprocedure"></div>

最佳答案

使用 jQuery,可以很容易地获取多个 select 标记中的所有值:

$(select).val()

现在你只需要检查里面是否存在'Other':

$(select).val().indexOf('Other') > -1

$('#s1').on('change', function() {
  if ($(this).val().indexOf('Other') > -1) {
    $('#otherprocedure').html('Other: <input type="text" name="episode_otherprocedure" style="width: 450px;"/>')
  } else {
    $('#otherprocedure').html('');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="s1" multiple="multiple" data-placeholder="Click to select..." size="7" name="episode_procedure[]" style="width: 450px;">
<option value="anterior resection">anterior resection</option>
<option value="appendicectomy">appendicectomy</option>
<option value="Other">Other</option></select>

<div id="otherprocedure"></div>

关于如果在多选输入中选择了 'Other',Javascript 显示/隐藏文本字段输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40434697/

相关文章:

javascript - 使用 jQuery 打开链接并自动滚动到特定的 div

jquery - 使用 jQuery UI 的对话框 ("destroy")将元素放在错误的位置?

javascript - 如何使 jQuery POST 函数打开新页面?

javascript - 返回表单会产生一个单独的 div 标记

javascript - 迭代复杂对象,删除不需要的元素(多个嵌套对象)

javascript - body 标签可以容纳乘法 onload ="setInterval()"吗?

javascript - 单击按钮生成物化选择

javascript - 如果标记 <ul> 之间为空,则发出警报。?

javascript - 在div外点击,隐藏div

javascript - 是否可以为 SVG 元素设置边框或线性渐变 - line