我有一个多元素和依赖div,要求用户先选择状态。一旦选择了州,它将为用户提供州内适当的城市。
<form method="post">
<div class="summary">
<div class="trip">
<select name="State" class="state">
<option selected disabled>Choose a State</option>
<option>California</option>
<option>New York</option>
</select>
<select name="City" class="city" disabled="true">
<option value="Z">Select a city</option>
</select>
<br><br>
</div>
</div>
jQuery的:
$(document).ready(function() {
$("#result").hide();
$("form").on("change", "select", function(){
var current = $(this).index();
if($(this).eq(current).val() == 'Z') {
$(".city").eq(current).html("<option>Select a city</option>");
$(".city").eq(current).attr('disabled', true);
}
else {
if($(this).eq(current).val() == 'California') {
$(".city").eq(current).html("<option>San Francisco</option><option>Los Angeles</option>");
$(".city option:first").eq(current).attr('selected', 'selected');
$(".city").eq(current).attr('disabled', false);
}
if($(this).eq(current).val() == 'New York') {
$(".city").eq(current).html("<option>New York City</option><option>Albany</option>");
$(".city option:first").eq(current).attr('selected', 'selected');
$(".city").eq(current).attr('disabled', false);
}
}
});
var maxAppend = 0;
$("#add").click(function() {
if (maxAppend >= 4) return;
var additional = $(".trip").html();
$(".trip").after(additional);
maxAppend++;
});
});
我想让用户最多添加四次“旅行”课程。当我使用append()或after()如上所示。新添加项的索引取决于1,这会导致第一次行中的选定项重置,因为它具有相同的索引。实现这个的正确和优雅的方法是什么?
这是指向jsfiddle的链接:https://jsfiddle.net/L2bfmo69/
答案 0 :(得分:1)
您可以使用解决方案https://jsfiddle.net/L2bfmo69/5/
$(document).ready(function() {
var additional = $(".trip").html();
$("#result").hide();
$("form").on("change", "select", function(){
var current = $(this).index();
if($(this).eq(current).val() == 'Z') {
$(".city").eq(current).html("<option>Select a fare</option>");
$(".city").eq(current).attr('disabled', true);
}
else {
if($(this).val() == 'California') {
$(this).next().html("<option>San Francisco</option><option>Los Angeles</option>");
$(this).next().attr('disabled', false);
}
if($(this).eq(current).val() == 'New York') {
$(this).next().html("<option>New York City</option><option>Albany</option>");
$(this).next().attr('disabled', false);
}
}
});
var maxAppend = 0;
$("#add").click(function() {
$(".summary").append('<div class="trip">' + additional + "</div>");
if ($('.summary').children().length >= 4) {
$('#add').prop('disabled', true);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post">
<div class="summary">
<div class="trip">
<select name="State" class="state">
<option selected disabled>Choose a State</option>
<option>California</option>
<option>New York</option>
</select>
<select name="City" class="city" disabled="true">
<option value="Z">Select a city</option>
</select>
<br><br>
</div>
</div>
<div id="nexttrip"></div>
<button type="button" id="add">Add another trip</button>
<br><br>
<input type="submit">
</form>
用户插入4后,我已禁用添加按钮。