我正在创建一个基本联系表单,其中包含下拉菜单并显示基于条件逻辑的其他下拉菜单。我正在使用JavaScript来做到这一点。我对JS很新,所以这就是我想出来的。它有效,但我的问题是,当您选择其中一个下拉选项时,即使您更改为其他选项,新选项也会保留在那里。有没有办法让它在每次从第一个下拉菜单中选择不同的选项时重置?
<body>
<h1>Price Quote</h1>
<h2>Request A Quote</h2>
<form id="price-quote">
<div class="form-group">
<label for="cleaning-service" class="control-label">Cleaning Service Requested</label>
<select class="form-control" onchange="serviceSelector(this);">
<option disabled selected value> -- select an option -- </option>
<option value="carpet-cleaning">Carpet Cleaning</option>
<option value="upholstery-cleaning">Upholstery Cleaning</option>
<option value="area-rug-cleaning">Area Rug Cleaning</option>
</select>
</div>
<!--carpet cleaning-->
<div id="carpet-services" style="display:none;">
<div class="form-group">
<!--how many bedrooms-->
<label class="control-label" for="carpet_cleaning">Bedrooms</label>
<select class="form-control" id="carpet_cleaning">
<option class="1-bedroom">1</option>
<option class="2-bedroom">2</option>
<option class="3-bedroom">3</option>
</select>
<!--how many dining rooms-->
<label class="control-label" for="carpet_cleaning">Dining Rooms</label>
<select class="form-control" id="carpet_cleaning">
<option>1</option>
<option>2</option>
</select>
<!--how many family rooms-->
<label class="control-label" for="carpet_cleaning">Family Rooms</label>
<select class="form-control" id="carpet_cleaning">
<option>1</option>
<option>2</option>
</select>
</div>
</div>
<!--upholstery cleaning-->
<div id="upholstery-services" style="display:none;">
<div class="form-group">
<!--how many dining room chairs-->
<label class="control-label" for="upholstery_cleaning">Dining Rooms Chairs (each)</label>
<select class="form-control" id="upholstery_cleaning">
<option class="1-dining-room-chair">1</option>
<option class="2-dining-room-chair">2</option>
</select>
<script>
function serviceSelector(that) {
if (that.value == "carpet-cleaning") {
document.getElementById("carpet-services").style.display = "block";
}
else if (that.value == "upholstery-cleaning") {
document.getElementById("upholstery-services").style.display = "block";
}
}
如果有更好的方法可以做到这一点 - 而且可能存在 - 我愿意改变它以使其更好地工作。如果这更容易,这里是JSFiddle的链接:https://jsfiddle.net/wcL72cr9/
谢谢
答案 0 :(得分:1)
您可以使用$("#carpet-services select,#upholstery-services select").prop('selectedIndex', 0);
我向您的主id
添加了select
,而不是使用onchange
事件,因为我遇到了与Fiddle有些问题。
自:
<select class="form-control" onchange="serviceSelector(this);">
要:
<select class="form-control" id="cleaning">
并将jquery更新为:
$("#cleaning").change(function () {
$("#carpet-services,#upholstery-services").hide();
$("#carpet-services select,#upholstery-services select").prop('selectedIndex', 0);
if (this.value == "carpet-cleaning") {
$("#carpet-services").show();
}
else if (this.value == "upholstery-cleaning") {
$("#upholstery-services").show();
}
});
Fiddle的更新示例:https://jsfiddle.net/wcL72cr9/5/