如何使用JQuery创建条件下拉菜单

How to create a conditional dropdown menu using JQuery?

本文关键字:条件 下拉菜单 创建 JQuery 何使用      更新时间:2023-09-26

我正试图根据另一个下拉列表的选择创建一个下拉菜单。如果选择了Brand PreferenceBrand Purchased,则应出现DIV select_a_brand。我使用以下代码。它隐藏DIV select_a_brand,但当我选择选项Brand PreferenceBrand Purchased时,DIV select_a_brand仍然隐藏。它没有显示。我该如何解决这个问题?

<div class="row">
    <label class="form_controller required">By Brand</label>
    <select style="width: 218px;">
        <option>Select an option</option>
        <option id="brand_preference">Brand Preference</option>
        <option id="brand_purchased">Brand Purchased</option>
    </select>
    <div id="select_a_brand">   
        <?php echo $form->dropDownList($model,'brand_id', gGetBrandList('brand_id', 'brand_id, brand_name'), array('prompt'=>'Select a brand')); ?> 
    </div>
    <script type="text/javascript">
        $(document).ready(function() {
            jQuery('#select_a_brand').hide();                   
            jQuery('#brand_preference').select(function(){
                jQuery('#select_a_brand').show();    
            });             
        });
    </script>           
</div>

您应该使用jquery的适当的变更事件处理程序;另外,您必须绑定到父选择框。我已经更改了jsfiddle,它现在运行良好:参考下面的代码:

 $(document).ready(function() {
    jQuery('#select_a_brand').hide();                   
    jQuery( "#base_option" ).change(function() {     

        if($(this).val() == "Brand Purchased" ){
           alert( "Handler for .change() called." );
        }
    });
});

select不是事件,它只是用于选择下拉列表的特定索引/值的api。