我需要使用 jquery 根据用户从下拉菜单中的选择来添加和删除输入字段。我能够实现添加输入字段功能。但是对删除部分感到困惑。谁能给我一些建议?这是演示 HTML 代码:
<div class="form-fields">
<table>
<tr><th><label for="id_NOA">Number of Applications:</label></th><td><select name="NOA" id="id_NOA">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select></td></tr>
<tr><th><label for="id_Ap_m">Application method 1:</label></th><td><select name="Ap_m" id="id_Ap_m">
<option value="" selected="selected">Select an application method</option>
<option value="1">Aerial</option>
<option value="2">Ground Sprayer</option>
</select></td></tr>
<tr><th><label for="id_Ar">Application rate:</label></th><td><input type="text" name="Ar" value="1" id="id_Ar" /></td></tr>
</table>
</div>
jQuery代码:
$(document).ready(function() {
i = 2;
$("label[for='id_Ar']").html('Application rate 1:');
$('#id_NOA').change(function() {
var count_c = $(this).val();
while (i <= count_c) {
if (i <= count_c) {
$('<tr><th><label for="id_Ap_m">Application method ' + i + ':</label></th><td><select name="Ap_m" id="id_Ap_m"><option value="" selected="selected">Select an application method</option><option value="1">Aerial</option><option value="2">Ground Sprayer</option></select></td></tr>').appendTo("table");
$('<tr><th><label for="id_Ar">Application rate ' + i + ':</label></th><td><input type="text" name="Ar" value="1" id="id_Ar" /></td></tr>').appendTo("table");
i++;
}
//this is the part I could not make it work
if (i>count_c){
$('.form-fields:last').remove();
i--;
}
}
});
});