簡體   English   中英

基於按鈕單擊使用Jquery填充選擇下拉列表

[英]Populate Select drop down list with Jquery based on button click

我有2個按鈕和一個選擇下拉列表

<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>隱藏時禁用它。 這樣,表單不會提交不可見的<select>

<select disabled id="subscriptions">
    <option value="default">Please Choose a Plan</option>
</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);
});

這應該為您工作。

如果您已經有了有效的代碼,只是不想在每次單擊按鈕時都繼續添加值,則只需在現有的buttonclick函數的開頭添加“ $('#subscriptions')。empty()”腳本,或在下面添加該函數在腳本的頂部。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM