如果在多个选择输入中选择了“其他”,Javascript显示/隐藏文本字段输入
问题描述:
恐怕我卡住了,我希望有一些社区智慧。如果在多个选择输入中选择了“其他”,Javascript显示/隐藏文本字段输入
我正在构建一个提交数据到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>
答
使用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>
你的代码工作。它创建输入点击与他人。然后你期待什么呢? – prasanth
@prasad,当您从'select'框中选择多个项目时,代码不起作用。你可以检查我的答案,例如如何用jquery做到这一点。 – Dekel