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

时间:2016-11-05 04:15:47

标签: javascript jquery forms multiple-select

我害怕被困,我希望有一些社区智慧。

我正在构建一个将数据提交到SQL数据库的HTML表单。其中一个表单字段是多选输入字段,用户可以在其中选择正在执行的操作类型。然后,该数组将以逗号分隔值的形式导出到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='';
        }
&#13;
   
<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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

使用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>