我尝试过以下解决方案:How to set the first option on a select box using jQuery?
我认为这些解决方案对我不起作用,因为我的形式不同。我有两个单选按钮,根据选择的单选按钮,显示一个下拉菜单。默认情况下,两个下拉菜单都是隐藏的 (style="display:none"
)。要显示和隐藏下拉菜单,我使用以下简单代码:
$("#contactRadioButton").click(function () {
$("#contactDropdown").show();
$("#companyDropdown").hide();
});
$("#companyRadioButton").click(function () {
$("#companyDropdown").show();
$("#contactDropdown").hide();
});
我尝试过的代码示例之一:
$('#contactSelect').change(function(){
$('#companySelect').val('');
});
$('#companySelect').change(function(){
$('#contactSelect').val('');
});
但我只需要提交一个带有值的下拉列表。现在,我可以单击联系人单选按钮
,然后在下拉列表中选择一个值。然后,我可以选择公司单选按钮
,然后将显示另一个下拉列表,我可以选择一个值。然后,两个下拉菜单都会有一个值。
我的完整表单代码(单选按钮和下拉菜单):
<div class="form-group">
<label class="control-label">Add contact or company?</label>
<div>
<div class="radio-custom radio-success radio-inline">
<input id="contactRadioButton" name="contact_relatie" type="radio" value="1">
<label for="contactRadioButton">Contact</label>
</div>
<div class="radio-custom radio-success radio-inline">
<input id="companyRadioButton" name="contact_relatie" type="radio" value="1">
<label for="companyRadioButton">Company</label>
</div>
</div>
</div>
<div class="form-group " id="contactDropdown" style="display:none">
<label for="name">Contact:</label>
<select class="form-control" data-plugin="selectpicker" data-live-search="true" id="contactSelect" name="contact_id"><option value="" selected="selected">-- Select Contact --</option> // rest of options..</select>
</div>
<div class="form-group " id="companyDropdown" style="display:none">
<label for="name">Company:</label>
<select class="form-control" data-plugin="selectpicker" data-live-search="true" id="companySelect" name="relation_id"><option value="" selected="selected">-- Select Company --</option> // rest of options..</select>
</div>
最佳答案
JS
$('#contactSelect').change(function(){
$('#companySelect option:first').prop('selected', 'selected');
});
$('#companySelect').change(function(){
$('#contactSelect option:first').prop('selected', 'selected');
});
HTML
<div class="form-group " id="contactDropdown" style="display:none">
<label for="name">Contact:</label>
<select class="form-control" data-plugin="selectpicker" data-live-search="true" id="contactSelect" name="contact_id"><option value="" selected="selected">-- Select Contact --</option> // rest of options..</select>
</div>
<div class="form-group " id="companyDropdown" style="display:none">
<label for="name">Company:</label>
<select class="form-control" data-plugin="selectpicker" data-live-search="true" id="companySelect" name="relation_id"><option value="" selected="selected">-- Select Company --</option> // rest of options..</select>
</div>
关于javascript - 如果另一个下拉列表选择发生更改,则重置一个下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35508771/