Dynamic <select> dropdown using Javascript

前端 未结 1 1591
你的背包
你的背包 2021-01-27 10:18

I have a HTML page with three dropdowns. Based on the first dropdown, options in the second will be displayed. I achieved it using the below code which I found online and its wo

1条回答
  •  情歌与酒
    2021-01-27 10:53

    Filtering down your third list isn't any different from filtering down the second list. In fact, if you apply your attributes in a structured way, you can do all the work in one event handler.

    Here's a running example:

    $("[data-child]").change(function() {
      //store reference to current select
      var me = $(this);
    
      //get selected group
      var group = me.find(":selected").val();
    
      //get the child select by it's ID
      var child = $("#" + me.attr("data-child"));
    
      //hide all child options except the ones for the current group, and get first item
      var newValue = child.find('option').hide().not('[data-group!="' + group + '"]').show().eq(0).val();
      child.trigger("change");
    
      //set default value
      child.val(newValue);
    });
    
    
    
    

    0 讨论(0)
提交回复
热议问题