jquery ajax加载数据选项选择
问题描述:
这里是我的html,将加载ajax调用。jquery 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改变输入字段对应的选项选择。如果我选择值为'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输入字段具有相同的值。
在此先感谢。
答
你在做什么是清空整个.other
股利。
相反,比较输入的数量是大于还是小于选定的数量。
如果所选的号码是更大的:添加字段
如果所选的号码是小:删除字段
如果所选的号码是一样的:无能为力
$(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>");
}
}
});
});
你可以创建一个jsfiddle,http://jsfiddle.net – dreamweiver