如何使用jquery操作select标签中的选项标签

时间:2018-02-22 01:16:03

标签: javascript jquery

我需要一些帮助。我有一个包含"汽车"和"商业"。 我需要做的是,如果我点击汽车,第二个下拉选项将被过滤。所有选项都带有字母" A"在最后一部分将显示。

我只需要使用javascript或jquery

Click here to see the option tags that I'm referring

1 个答案:

答案 0 :(得分:0)

'所以,在你的JQuery中(这个块应该存在于脚本标签或页面的导入脚本文件中):

 //document.ready() fires once the DOM has fully loaded, in otherwords all elements of the document have been rendered, 
 //you can then access them to do what we are doing here, which is attaching an event listener to your 1st drop down, 
 //and then inside that event's function do your second drop downs filtering based on the selection in drop down 1
        document.ready(function(){
            //The pound sign indicates the Id property of the element
            //In $(#dropDown1) replace the word dropDown1 with your drop down's actual Id
            $('#dropDown1').on('change', function(){
               //$(this) gets you the drop down element and .find() searches for the nearest decendant that meets the selector requirement, 
           //in this case element with tag option and attribute 'selected'
               if($(this).find('option:selected').text() === 'Automotive'){
                     //Do filtering of drop down 2 for Automotive selection
                     //Iterate your options, if they dont have a last letter
                     //equal to a or A hide() the element
                     //Do similar action when Commercial selected
                     $('#dropDown2 option').each(function(i, ele){
                         let lastChar = $(ele).text()[$(ele).text().length - 1];
                         if(lastChar !== 'A' && lastChar !== 'a'){
                            $(ele).hide();
                         }
                     });
               }else{
                     //Do filtering of drop down 2 for Commercial selection
                     //Change this to else if if you ever have more than 2 options
               }
             });
        });