这是我的html,它将加载ajax调用。
<select id="choice-id" name="choice_name">
<option value="2">2</option>
<option value="3" selected="">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
<div style="display: block;" id="select" class="other">
<input id="other-0" name="other_0" type="text" value="abc">
<input id="other-1" name="other_1" type="text" value="pqr">
<input id="other-2" name="other_2" type="text" value="rst">
</div>
这是我的jquery,用于更改与选项select相对应的输入字段。如果我选择值为'6'的选项,它将生成6个没有任何值的输入字段。
$(document).on('change','#choice-id',function() {
var choicesizeSelected = $("#choice-id :selected").val();
$('.other').empty();
for(var i=0; i<choicesizeSelected; i++) {
$('.other').append("<input id='other-"+i+"' type='text' name='other_"+i+"'></input>");
}
}
这段代码完美无缺。但如果我再次选择默认选项3,我希望返回默认3输入字段具有相同的值。
提前感谢。
答案 0 :(得分:1)
您正在做的是清空整个.other
div。
相反,请比较输入的数量是大于还是小于选定的数量。
如果所选的数字更大:添加字段
如果所选数字较小:删除字段
如果所选的号码相同:什么都不做
$(function() {
$('#choice-id').on('change', function() {
var newNum = $(this).find(':selected').val();
var oldNum = $('.other input').length;
if( oldNum > newNum ) {
var x = parseInt(newNum)+1;
$('.other input:nth-child(n+'+x+')').remove();
}
else if( oldNum < newNum ) {
for( var i=oldNum; i<newNum; i++ ) {
$('.other').append("<input id='other-"+i+"' type='text' name='other_"+i+"'></input>");
}
}
});
});