显示/隐藏文本字段输入if 'Other'在多选择输入中选择

Javascript show/hide text field input if 'Other' selected in multiple select input

本文关键字:选择 输入 Other 隐藏 if 显示 文本 字段      更新时间:2023-09-26

恐怕我被卡住了,我希望能得到一些社区智慧。

我正在构建一个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>