【问题标题】:Javascript show/hide text field input if 'Other' selected in multiple select input如果在多选输入中选择了“其他”,则 Javascript 显示/隐藏文本字段输入
【发布时间】:2016-11-05 04:15:46
【问题描述】:

恐怕我被困住了,我希望获得一些社区智慧。

我正在构建一个将数据提交到 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='';
        }
   
<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>

【问题讨论】:

  • 您的代码正在运行。它是通过其他人的输入点击创建的。那么您期待什么?
  • @prasad,当您从 select 框中选择多个项目时,代码不起作用。您可以查看我的答案,例如如何使用 jquery 进行操作。

标签: javascript jquery forms multiple-select


【解决方案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>

【讨论】:

    猜你喜欢
    • 2022-06-13
    • 1970-01-01
    • 1970-01-01
    • 2021-10-01
    • 1970-01-01
    • 2017-08-11
    • 2015-06-12
    • 2020-12-28
    • 2020-11-08
    相关资源
    最近更新 更多