【问题标题】:Populate Select drop down list with Jquery based on button click基于按钮单击使用 Jquery 填充选择下拉列表
【发布时间】:2014-09-25 13:16:24
【问题描述】:

我有 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,但即使年份选择被隐藏,表单也会同时提交它们,所以我不知道实际选择的是哪个。所以它必须是一个选择下拉

【问题讨论】:

  • 你能给我们一个jsfiddle吗?
  • 你可以调用 $("#subscriptions").empty();在每次添加选项之前
  • 尝试使用两个选择并将其隐藏,但使用 $('select#select-to-disable').prop('disabled', true);请参阅我对更多详细信息的回答。

标签: javascript php jquery html forms


【解决方案1】:

您可以尝试使用两个选择,但仅 .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);
});

这应该对你有用。

【讨论】:

    【解决方案2】:

    您可以在隐藏时禁用&lt;select&gt;。这样表单不会提交不可见的&lt;select&gt;

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

    【讨论】:

      【解决方案3】:

      如果您已经有工作代码并且不想在每次单击按钮时继续添加值,只需在现有按钮单击函数的开头添加“$('#subscriptions').empty()”脚本或添加脚本顶部的以下函数。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多