我有一个多选下拉列表,选择的文本区域附加在 div 中。
下面是代码:
jQuery('#proprtyid').change(function () {
var texts = document.getElementById("texts");
var countoptions = jQuery(".propertiesselectbox :selected").length;
texts.innerHTML = "";
x=[];
jQuery(".propertiesselectbox").children(':selected').each(function(){
x.push(jQuery(this).text());
});
for(i=0; i < countoptions; i++) {
texts.innerHTML += '<p style="margin:20px 0 5px 0;">Please add the description for: <b>' + x[i] + '</b></p><textarea style="display: block;margin:0px 0 20px 0;" rows="4" cols="50" name="propnotes_'+ i +'" /></textarea>';
}
});
所以问题是,我做了一个选择,并根据 jquery 的长度,我将这些数量的文本区域附加到 div 并在其中添加了文本,现在在进行新选择后,我之前生成的所有文本区域都被删除了,我不想要:(
有没有办法在进行新选择时保留这些文本区域?
我已经搜索并使用了 stack-overflow 中提供的每个示例,但没有一个可以帮助我。
提前致谢。
最佳答案
首先我不喜欢混合jquery和纯javascript..所以我会用jquery编写代码
第二如果您需要我对此的意见..我可以说您选择了一种困难的方式来实现这一点..您可以通过简单的方式'append() ' #texts
中的所有选项都会加载并在选择更改时显示/隐藏它们
类似这样的事情
$(document).ready(function(){
var texts = $("#texts");
// append divs for each select option
$("#proprtyid option").each(function(i){
var getText = $(this).text();
texts.append('<div data-option="'+i+'"><p style="margin:20px 0 5px 0;">Please add the description for: <b>' + getText + '</b></p><textarea style="display: block;margin:0px 0 20px 0;" rows="4" cols="50" name="propnotes_'+ i +'" /></textarea></div>');
});
// hide all divs
$('div[data-option]').hide(0);
// select change event
$('#proprtyid').change(function () {
//loop through options
$(this).find('option').each(function(index){
if(this.selected){
$('div[data-option='+ index +']').show(0);
}else{
$('div[data-option='+ index +']').hide(0);
}
});
}).change();
});
工作演示
$(document).ready(function(){
var texts = $("#texts");
// append divs for each select option
$("#proprtyid option").each(function(i){
var getText = $(this).text();
texts.append('<div data-option="'+i+'"><p style="margin:20px 0 5px 0;">Please add the description for: <b>' + getText + '</b></p><textarea style="display: block;margin:0px 0 20px 0;" rows="4" cols="50" name="propnotes_'+ i +'" /></textarea></div>');
});
// hide all divs
$('div[data-option]').hide(0);
// select change event
$('#proprtyid').change(function () {
//loop through options
$(this).find('option').each(function(index){
if(this.selected){
$('div[data-option='+ index +']').show(0);
}else{
$('div[data-option='+ index +']').hide(0);
}
});
}).change();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="proprtyid" multiple>
<option value="1">1</option>
<option value="2">2</option>
<option selected value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<div id="texts"></div>
关于javascript - jQuery:保留下拉更改时生成的动态文本区域中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44052234/