使用jQuery根据第一个下拉列表选项更改第二个下拉列表。

40
我有两个下拉选择框:
<select name="select1" id="select1">
    <option value="1">Fruit</option>
    <option value="2">Animal</option>
    <option value="3">Bird</option>
    <option value="4">Car</option>
</select>

<select name="select2" id="select2">
    <option value="1">Banana</option>
    <option value="1">Apple</option>
    <option value="1">Orange</option>
    <option value="2">Wolf</option>
    <option value="2">Fox</option>
    <option value="2">Bear</option>
    <option value="3">Eagle</option>
    <option value="3">Hawk</option>
    <option value="4">BWM<option>
</select>

如果我在第一个选择框中选择了水果,如何使用 jQuery 实现只在第二个选择框中显示水果 - 香蕉、苹果和橙子。如果我选择了鸟类,第二个选择框将只显示鸟类 - 鹰和隼。依此类推...

我尝试用以下这段 jQuery 代码实现:

$("#select1").change(function() {
    var id = $(this).val();
    $('#select2 option[value!='+id+']').remove();
});

不幸的是,它几乎删除了所有内容,而我不知道如何恢复某些选项。我也读到了一些有关克隆的东西,但我不知道如何在这种情况下使用它。


这篇文章可能会帮助您的问题:https://dev59.com/QWLVa4cB1Zd3GeqPz9Bd - sujal
@santo,不幸的是,hide 只适用于 Firefox。 - Randy
@Randy 再看一遍,我有一个问题;当您提交表单时,您将如何传递 select2 的所选值?这些值不是唯一的,那么什么区分香蕉和苹果? - Ja͢ck
@杰克,这只是一个例子。我还为所有选择选项添加了唯一的名称。 - Randy
@Randy 好的,那是你的权利,当你提交表单时只是额外的工作 :) - Ja͢ck
8个回答

75

$("#select1").change(function() {
  if ($(this).data('options') === undefined) {
    /*Taking an array of all options-2 and kind of embedding it on the select1*/
    $(this).data('options', $('#select2 option').clone());
  }
  var id = $(this).val();
  var options = $(this).data('options').filter('[value=' + id + ']');
  $('#select2').html(options);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<select name="select1" id="select1">
  <option value="1">Fruit</option>
  <option value="2">Animal</option>
  <option value="3">Bird</option>
  <option value="4">Car</option>
</select>


<select name="select2" id="select2">
  <option value="1">Banana</option>
  <option value="1">Apple</option>
  <option value="1">Orange</option>
  <option value="2">Wolf</option>
  <option value="2">Fox</option>
  <option value="2">Bear</option>
  <option value="3">Eagle</option>
  <option value="3">Hawk</option>
  <option value="4">BWM<option>
</select>

使用jQuery data() 存储数据

我猜隐藏元素在跨浏览器上不起作用(2012年),我自己没有测试过。


1
@sabithpocker,当然我标记了它。 有一个小问题。我应该添加什么代码,使得当页面刚加载或刷新时,第二个选择框已经只显示水果选项-香蕉、苹果、橙子;而不是所有选项。 - Randy
2
@Randy $("#select1").trigger('change'); 这样你可以显式地调用 change 事件。或者只需使用 $('#select1').change(); 就可以达到同样的效果。 - sabithpocker
这个问题在于,如果这是一个表单,你无法确定选择了哪个 #select2 选项,因为它们都具有相同的值。在 HTML5 中,我使用了 <option data-value=...>,正确的值将被发送到服务器。 - Gadi
3
上面的答案很好,我并没有做太多修改。只是我注意到如果我在表格中使用它,无法区分“香蕉”、“苹果”和“橙子”,因为它们都具有相同的值(1)。添加"data-value"可以解决这个问题。 - Gadi
1
@Mauliardiwinoto,您需要使用$(this).data('optionsForThird'...来存储第三个选择选项,并进行筛选。请清楚地解释您的场景,例如这3个选择器如何相互关联。您可以发布一个问题,然后在此处添加链接作为评论。 - sabithpocker
显示剩余8条评论

11

我想制作一个使用$.getJSON()从单独的JSON文件获取数据的版本。

演示:这里

JavaScript:

$(document).ready(function () {
    "use strict";

    var selectData, $states;

    function updateSelects() {
        var cities = $.map(selectData[this.value], function (city) {
            return $("<option />").text(city);
        });
        $("#city_names").empty().append(cities);
    }

    $.getJSON("updateSelect.json", function (data) {
        var state;
        selectData = data;
        $states = $("#us_states").on("change", updateSelects);
        for (state in selectData) {
            $("<option />").text(state).appendTo($states);
        }
        $states.change();
    });
});

HTML:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
    <select id="us_states"></select>
    <select id="city_names"></select>
    <script type="text/javascript" src="updateSelect.js"></script>
</body>
</html>

JSON:

{
    "NE": [
        "Smallville",
        "Bigville"
    ],
    "CA": [
        "Sunnyvale",
        "Druryburg",
        "Vickslake"
    ],
    "MI": [
        "Lakeside",
        "Fireside",
        "Chatsville"
    ]
}

9

将所有 #select2 的选项存储在一个变量中,根据 #select1 中选择的选项的值进行过滤,并使用 .html()#select2 中设置它们:

var $select1 = $( '#select1' ),
    $select2 = $( '#select2' ),
    $options = $select2.find( 'option' );

$select1.on('change', function() {
    $select2.html($options.filter('[value="' + this.value + '"]'));
}).trigger('change'); 

Here's a fiddle


@billyonecan。感谢您的代码,看起来很容易理解,但如果我有两个以上的选项,如何根据前两个选项显示呢?您能在fiddle中解释一下吗? - jvk

2

我在sabithpocker的想法基础上进行了改进,制作了一个更通用的版本,可以让您从给定的触发器控制多个选择框。

我将我想要控制的选择框分配了类名“switchable”,并像这样克隆了它们所有:

$j(this).data('options',$j('select.switchable option').clone());

我使用了特定的命名约定来处理可切换的选项,这也可以转化为类。在我的情况下,“category”和“issuer”是选择器名称,“category_2”和“issuer_1”是类名称。

之后,我在select.switchable组上运行了$.each循环,在函数内部使用$(this)的副本:

var that = this;
$j("select.switchable").each(function() { 
    var thisname = $j(this).attr('name');
    var theseoptions = $j(that).data('options').filter( '.' + thisname + '_' + id );
    $j(this).html(theseoptions);
});     

通过在需要控制的元素上使用类名,该函数将安全地忽略页面中其他选择器(例如Fiddle示例中的最后一个选择器)。

这里是完整代码的Fiddle


1
我已经找到了解决方案,如下所示... 对我来说完美地工作 :)
$(document).ready(function(){
$("#selectbox1").change(function() {
    var id = $(this).val();
    $("#selectbox2").val(id);
 });   });

1
所有这些方法都很棒。我发现另一个简单的资源,是使用"onchange"和AJAX来创建动态表单的一个很好的例子。

http://www.w3schools.com/php/php_ajax_database.asp

我只是修改了文本表格输出,以另一个选择下拉列表的形式呈现,根据第一个下拉列表的选择进行填充。对于我的应用程序,用户将选择一个州,然后第二个下拉列表将被填充为所选州的城市。与上面的JSON示例类似,但使用php和mysql。

0

尝试使用它:

下拉框依赖于另一个下拉框中选择的选项。使用jQuery根据第一个下拉列表选项更改第二个选择列表。

<asp:HiddenField ID="hdfServiceId" ClientIDMode="Static" runat="server" Value="0" />
<asp:TextBox ID="txtOfferId" CssClass="hidden" ClientIDMode="Static" runat="server" Text="0" />
<asp:HiddenField ID="SelectedhdfServiceId" ClientIDMode="Static" runat="server" Value="0" />
<asp:HiddenField ID="SelectedhdfOfferId" ClientIDMode="Static" runat="server" Value="0" />

<div class="col-lg-2 col-md-2 col-sm-12">
    <span>Service</span>
    <asp:DropDownList ID="ddlService" ClientIDMode="Static" runat="server" CssClass="form-control">
    </asp:DropDownList>
</div>
<div class="col-lg-2 col-md-2 col-sm-12">
    <span>Offer</span>
    <asp:DropDownList ID="ddlOffer" ClientIDMode="Static" runat="server" CssClass="form-control">
    </asp:DropDownList>
</div>

在你的网页中使用jQuery库。
<script type="text/javascript">
    $(document).ready(function () {
        ucBindOfferByService();
        $("#ddlOffer").val($('#txtOfferId').val());
    });

    $('#ddlOffer').on('change', function () {
        $("#txtOfferId").val($('#ddlOffer').val());
    });

    $('#ddlService').on('change', function () {
        $("#SelectedhdfOfferId").val("0");
        SetServiceIds();
        var SelectedServiceId = $('#ddlService').val();
        $("#SelectedhdfServiceId").val(SelectedServiceId);
        if (SelectedServiceId == '0') {
        }
        ucBindOfferByService();
        SetOfferIds();
    });

    function ucBindOfferByService() {
        GetVendorOffer();
        var SelectedServiceId = $('#ddlService').val();
        if (SelectedServiceId == '0') {
            $("#ddlOffer").empty();
            $("#ddlOffer").append($("<option></option>").val("0").html("All"));
        }
        else {
            $("#ddlOffer").empty();
            $(document.ucVendorServiceList).each(function () {
                if ($("#ddlOffer").html().length == "0") {
                    $("#ddlOffer").append($("<option></option>").val("0").html("All"));
                }
                $("#ddlOffer").append($("<option></option>").val(this.OfferId).html(this.OfferName));
            });
        }
    }

    function GetVendorOffer() {
        var param = JSON.stringify({ UserId: $('#hdfUserId').val(), ServiceId: $('#ddlService').val() });
        AjaxCall("DemoPage.aspx", "GetOfferList", param, OnGetOfferList, AjaxCallError);
    }

    function OnGetOfferList(response) {
        if (response.d.length > 0)
            document.ucVendorServiceList = JSON.parse(response.d);
    }

    function SetServiceIds() {
        var SelectedServiceId = $('#ddlService').val();
        var ServiceIdCSV = ',';
        if (SelectedServiceId == '0') {
            $('#ddlService > option').each(function () {

                ServiceIdCSV += $(this).val() + ',';
            });
        }
        else {
            ServiceIdCSV += SelectedServiceId + ',';
        }
        $("#hdfServiceId").val(ServiceIdCSV);
    }

    function SetOfferIds() {
        var SelectedServiceId = $('#ddlService').val();
        var OfferIdCSV = ',';
        if (SelectedServiceId == '0') {
            $(document.ucVendorServiceList).each(function () {
                OfferIdCSV += this.OfferId + ',';
            });
        }
        else {
            var SelectedOfferId = $('#ddlOffer').val();
            if (SelectedOfferId == "0") {
                $('#ddlOffer > option').each(function () {
                    OfferIdCSV += $(this).val() + ',';
                });
            }
            else {
                OfferIdCSV += SelectedOfferId + ',';
            }
        }
    }
</script>

在您的网页中使用后端代码。

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        ServiceList();
    }
}

public void ServiceList()
{
    ManageReport manageReport = new ManageReport();
    DataTable ServiceList = new DataTable();
    ServiceList = manageReport.GetServiceList();
    ddlService.DataSource = ServiceList;
    ddlService.DataTextField = "serviceName";
    ddlService.DataValueField = "serviceId";
    ddlService.DataBind();
    ddlService.Items.Insert(0, new ListItem("All", "0"));
}

public DataTable GetServiceList()
{
    SqlParameter[] PM = new SqlParameter[]
    {
        new SqlParameter("@Mode"    ,"Mode_Name"    ),
        new SqlParameter("@UserID"  ,UserId         )
    };
    return SqlHelper.ExecuteDataset(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, "Sp_Name", PM).Tables[0];
}

[WebMethod]
public static String GetOfferList(int UserId, String ServiceId)
{
    var sOfferList = "";
    try
    {
        CommonUtility utility = new CommonUtility();
        ManageReport manageReport = new ManageReport();
        manageReport.UserId = UserId;
        manageReport.ServiceId = ServiceId;
        DataSet dsOfferList = manageReport.GetOfferList();
        if (utility.ValidateDataSet(dsOfferList))
        {
            //DataRow dr = dsEmployerUserDepartment.Tables[0].NewRow();
            //dr[0] = "0";
            // dr[1] = "All";
            //dsEmployerUserDepartment.Tables[0].Rows.InsertAt(dr, 0);
            sOfferList = utility.ConvertToJSON(dsOfferList.Tables[0]);
        }
        return sOfferList;
    }
    catch (Exception ex)
    {
        return "Error Message: " + ex.Message;
    }
}

public DataSet GetOfferList()
{
    SqlParameter[] sqlParameter = new SqlParameter[]
        {                                                                     
            new SqlParameter("@Mode"        ,"Mode_Name"    ),
            new SqlParameter("@UserID"      ,UserId         ),
            new SqlParameter("@ServiceId"   ,ServiceId      )
        };
    return SqlHelper.ExecuteDataset(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, "Sp_Name", sqlParameter);
}

0
在所选答案中,我看到当页面最初加载时,第一个选项的选择是固定的,因此提供了选择2中所有类别的选项。 您可以通过在两个选择标记中将第一个选项添加为以下内容来避免这种情况: <option value="none" selected disabled hidden>选择一个选项</option>
<select name="select1" id="select1">
<option value="none" selected disabled hidden>Select an Option</option>
<option value="1">Fruit</option>
  <option value="2">Animal</option>
  <option value="3">Bird</option>
  <option value="4">Car</option>
</select>


<select name="select2" id="select2">
<option value="none" selected disabled hidden>Select an Option</option>
  <option value="1">Banana</option>
  <option value="1">Apple</option>
  <option value="1">Orange</option>
  <option value="2">Wolf</option>
  <option value="2">Fox</option>
  <option value="2">Bear</option>
  <option value="3">Eagle</option>
  <option value="3">Hawk</option>
  <option value="4">BWM<option>
</select>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接