I have 2 buttons and a select dropdown list
<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>
On the button click of month i need the select drop down list populated with 4 choices. Or the click of year the list needs to be populated with the 4 year choices. But if you go back and forth between month and year i need the list to not have 1000 of the same choices.
I used jquery .show and .hide on two different selects but the form was submitting both of them even if the year select was hidden so I didnt know which was actually chosen. So it has to be one select drop down
You can use two selects as you tried, but just .hide() does not remove it from the form. To remove it from form you can disable it, using $.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>
In 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);
});
This should work to you.
You can disable the <select>
while it is hidden. In this way the form does not will submit the invisible <select>
<select disabled id="subscriptions">
<option value="default">Please Choose a Plan</option>
</select>
If you already have working code and just want to not keep on adding values on every button click, just add the "$('#subscriptions').empty()" script in beginning of of your existing buttonclick functions or add the function below at the top of your scripts.
$('#btnmonth, #btnyear').click(function() {
$('#subscriptions').empty()
});