我试图让DIV"乘客"根据" numpass"。
中选择的值克隆自身这只是总代码的一小部分,因为它有很多细节,所以它只有几百行。我尝试了多种方法,到目前为止没有任何工作。我对Javascript比较陌生,所以任何回复的解释都会很好。
HTML
<table>
<tr>
<td class="form_label">Number of Passengers</td>
<td>
<select id="numpass" name="numpass" class="form_e"/>
<option value="1" selected="selected">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option></td>
</tr>
</table>
<div id="passenger">
<div class="form_head">Passenger Details</div>
<br />
<table width="100%">
<tr>
<td class="form_label">First Name: <input type="text" name="cust_fname[]" class="form_f"/> Last Name: <input type="text" name="cust_lname[]" class="form_f"/> Phone: <input type="text" name="phone[]" class="form_g" /> Weight (kg): <input type="text" name="weight[]" class="form_a" /></td>
</tr>
</table>
答案 0 :(得分:0)
考虑使用for
循环:
$('.numPax').onChange(function(){
// Clear all but the first (consider if they change the value twice)
$('.passenger').not(':first').remove();
var currentNumPax = $('.passenger').length;
var newNumPax = currentNumPax+1;
var lastRepeatDiv = $('.passenger').last();
for(i = 0; i < currentNumPax; i++) {
var newDiv = lastRepeatingDiv.clone();
newDiv.insertAfter(lastRepeatingDiv);
newDiv.find("input").each(function (index, input) {
input.name = input.name.replace("_" + currentCount, "_" + i);
});
});
}
答案 1 :(得分:0)
这是我想出的。
的Javascript
$('#numPax').change(function() {
$('.passenger').not(':first').remove(); //remove all but the first
var currentNumPax = $(this).val(); // get the value from the select
var newDiv, i;
for(i = 0; i < currentNumPax; i++) {
newDiv = $('.passenger').first().clone();
$('#container').append(newDiv);
}
});
HTML
<table>
<tr>
<td class="form_label">Number of Passengers</td>
<td>
<select id="numPax" name="numPax" class="form_e" >
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
</td>
</tr>
</table>
<div id="container">
<div class="passenger">
<div class="form_head">Passenger Details</div>
<br />
<table width="100%">
<tr>
<td class="form_label">First Name: <input type="text" name="cust_fname_1" class="form_f"/> Last Name: <input type="text" name="cust_lname_1" class="form_f"/> Phone: <input type="text" name="phone_1" class="form_g" /> Weight (kg): <input type="text" name="weight_1" class="form_a" />
</td>
</tr>
</table>
</div>
</div>