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

Javascript 基于按钮单击使用Jquery填充选择下拉列表,javascript,php,jquery,html,forms,Javascript,Php,Jquery,Html,Forms,我有两个按钮和一个选择下拉列表 <button type="button" name="btnmonth" id="btnmonth">Monthly</button> <button type="button" name="btnyear" id="btnyear" >Yearly</button> <select id="subscriptions"> <option value="default">Pleas

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

<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,但是表单提交了这两个选择,即使年份选择是隐藏的,所以我不知道实际选择了哪一个。因此,它必须是一个选择下拉列表

您可以在隐藏时禁用。这样表单就不会提交不可见的内容


您可以在尝试时使用两个选项,但“隐藏”不会将其从窗体中删除。 要从表单中删除它,可以使用$.prop'disabled',布尔值禁用它


这应该对您有用。

如果您已经有了工作代码,并且不想在每次单击按钮时都继续添加值,只需添加$“订阅”。在现有按钮的开头空脚本单击函数或在脚本顶部添加下面的函数

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

你能给我们一个jsfiddle吗?你可以调用$subscriptions.empty;在每次添加选项之前,请尝试使用两个选择并按照您所说的将其隐藏,但请使用$'selectselect-to-disable'.prop'disabled',true禁用隐藏的选择;更多细节请参见我的答案。
<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>
$('#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);
});
$('#btnmonth, #btnyear').click(function() {
    $('#subscriptions').empty()
});