使用Jquery基于按钮单击填充选择下拉列表


Populate Select drop down list with Jquery based on button click

我有两个按钮和一个选择下拉列表

<button type="button" name="btnmonth" id="btnmonth">Monthly</button>
<button type="button" name="btnyear" id="btnyear" >Yearly</button>
<select id="subscriptions">
    <option value="default">Please Choose a Plan</option>
</select>

在每月的按钮点击上,我需要填充选择下拉列表4种选择。或者点击年份列表需要填充4年的选项。但如果你在一个月和一年之间来回奔波,我需要这份清单上没有1000个相同的选择。

我在两个不同的选择中使用了jquery.show和.hide,但表格同时提交了这两个选择,即使年份选择是隐藏的,所以我不知道哪一个是真正选择的。所以它必须是一个选择下拉

您可以在尝试时使用两个select,但只是.hide()并不能将其从表单中删除。要将其从表单中删除,您可以使用$.prop('disabled', boolean) 禁用它

<button type="button" name="btnmonth" id="btnmonth">Monthly</button>
<button type="button" name="btnyear" id="btnyear" >Yearly</button>
<select id="subscriptions-monthly" style="display: none" disabled>
    <!-- Monthly select options -->
</select>
<select id="subscriptions-yearly" style="display: none" disabled>
    <!-- Monthly select options -->
</select>

在javascript:中

$('#btnmonth').click(function(event) {
    $("#subscriptions-yearly").hide().prop('disabled', true);
    $("#subscriptions-monthly").show().prop('disabled', false);
});
$('#btnmonth').click(function(event) {
    $("#subscriptions-monthly").hide().prop('disabled', true);
    $("#subscriptions-yearly").show().prop('disabled', false);
});

这应该对你有用。

您可以在<select>隐藏时禁用它。通过这种方式,表单不会提交不可见的<select>

<select disabled id="subscriptions">
    <option value="default">Please Choose a Plan</option>
</select>

如果您已经有了工作代码,并且不想在每次单击按钮时都不断添加值,只需在现有buttonclick函数的开头添加"$('#subscription').empty()"脚本,或者在脚本的顶部添加下面的函数。

$('#btnmonth, #btnyear').click(function() {
    $('#subscriptions').empty()
});