我正在尝试添加一个基于“其他”的文本区域作为数组中的选项之一。
这是代码。
首先是 div 和 select 语句
<div id="refertodiv">
<label for="referto">Refer to:</label>
<select multiple="multiple" name="referto" id="referto">
<option value="1">Infection Control</option>
<option value="2">Medical</option>
<option value="3">Nursing Administration</option>
<option value="4">Personnel</option>
<option value="5">Quality Committee</option>
<option value="6">Risk and Safety</option>
<option value="7">Other</option>
</select>
</div>
这是函数。
$(function(){
$("#referto").change(function(){
var rechange = [];
$('#referto :selected').each(function(){
rechange[$(this).val()]=$(this).text();
});
var textarea = "<textarea name='referother' id='referother' />";
if($.inarray("Other",rechange)>-1){
$("#referto").append(textarea);
}
})
})
最佳答案
您根本不需要使用数组。如果选择了其他,此代码将添加文本区域;如果取消选择其他,则删除文本区域。
这是一个 fiddle :http://jsfiddle.net/LimitedWard/3GKm5/1/
$("#referto").change(function(){
var otherSelected = false;
$('#referto option:selected').each(function(){
if ($(this).text() == "Other")
{
otherSelected = true;
}
});
if (otherSelected) /* add textarea if otherSelected was true */
{
var textarea = "<textarea name='referother' id='referother' />";
$("#referto").after(textarea);
}
else /* remove textarea if otherSelected was false */
{
$("#referother").remove();
}
});
请注意,您使用的是 .append()
它将文本区域放置在 <select>
内元素,而我使用 .after()
它将文本区域放置在 <select>
之后元素。将文本区域放入另一个输入中是无效的。
关于javascript - 我正在尝试添加一个基于“其他”被选为选择中的多个选择之一的文本区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24537930/