gpt4 book ai didi

javascript - 如何在单击复选框时创建下拉菜单?

转载 作者:行者123 更新时间:2023-12-03 06:53:25 25 4
gpt4 key购买 nike

这是我的复选框和下拉菜单:

<label>
<input type="checkbox" name="check_list[]" Value="Castle Connolly Regional Top Doctor" />Castle Connolly Regional Top Doctor</label>
<select name="check_year[]"></select>
<label>
<input type="checkbox" name="check_list[]" Value="Castle Connolly Top U.S. Doctor" id="ccn" />Castle Connolly Top U.S. Doctor</label>
<select name="check_year[]"></select>
<label>
<input type="checkbox" name="check_list[]" Value="Vitals Compassionate Doctor" />Vital's Compassionate Doctor Recognition</label>
<select name="check_year[]"></select>
<label>
<input type="checkbox" name="check_list[]" Value="Super Doctor" />Super Doctor</label>
<select name="check_year[]"></select>

我最初尝试将它们捕获在数组中,然后将它们连接到一个变量中,然后插入到数据库中,但是如果数组的长度不同,那就很困难。我认为最好只在选择其中一个框时才显示下拉菜单,那么我如何在 JavaScript 中做到这一点呢?

最佳答案

我认为使用 jQuery 实现这一目标的最简单方法是:

// select the <input> elements whose 'type' attribute is equal
// to 'checkbox', and bind the anonymous function of the on()
// method as the event handler for the named ('change') event(s):
$('input[type=checkbox]').on('change', function(){

// find the first ancestor <label> element of the current
// <input>, find the next sibling that matches the selector
// (to ensure that we're working only with <select> elements,
// and set its 'disabled' property to false when the the
// checkbox is checked (so !true) and to true when the checkbox
// is not checked:
$(this).closest('label').next('select').prop('disabled', !this.checked);

// fire the change event on each of the checkboxes on page-load,
// to appropriately disable/enable the <select> elements:
}).change();

$('input[type=checkbox]').on('change', function() {
$(this).closest('label').next('select').prop('disabled', !this.checked);
}).change();
label {
margin: 0.5em 1em 0 0;
}
label::before {
content: '';
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
<input type="checkbox" name="check_list[]" Value="Castle Connolly Regional Top Doctor" />Castle Connolly Regional Top Doctor</label>
<select name="check_year[]"></select>
<label>
<input type="checkbox" name="check_list[]" Value="Castle Connolly Top U.S. Doctor" id="ccn" />Castle Connolly Top U.S. Doctor</label>
<select name="check_year[]"></select>
<label>
<input type="checkbox" name="check_list[]" Value="Vitals Compassionate Doctor" />Vital's Compassionate Doctor Recognition</label>
<select name="check_year[]"></select>
<label>
<input type="checkbox" name="check_list[]" Value="Super Doctor" />Super Doctor</label>
<select name="check_year[]"></select>

JS Fiddle demo .

引用文献:

关于javascript - 如何在单击复选框时创建下拉菜单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37400668/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com