Javascript隐藏/显示部分无法重置

时间:2014-05-14 14:37:56

标签: javascript jquery html css jquery-ui

我根据一些选项选择显示并隐藏div。

有一个下拉列表,其中包含选项'已启用和已禁用' .once用户选择已启用需要显示div else否则隐藏div。

根据下拉选项选择隐藏/显示div工作正常,但是 如果已禁用,则为已配置的值。当我加载页面时,div将被隐藏(工作正常),然后我将选择Enabled,然后div显示但是.......当我点击重置选项时, 下拉选项返回到已禁用但Div部分应隐藏

这里我的代码是这样的,保护开关是从烧瓶中收到的wtform字段

{{form.protection_switch}}
            <div align="center" >
            <button class="btn btn-info btn-sm" type="submit"><i class="icon-ok bigger-110"></i>Submit</button>
            &nbsp; &nbsp; &nbsp;
            <button class="btn btn-sm" type="reset"><i class="icon-undo bigger-110"></i>Reset</button>
            </div>

部分应隐藏或显示

<div id="protection_data"></br> 
    <table id="grid-table"></table>
    <div id="grid-pager"></div>
</div>

Jquery代码

function protection_selected() {
        if ($('#protection_switch option:selected').val() == '0') {
            $('#protection_data').hide();
        } else  if ($('#protection_switch option:selected').val() == '1') {
            $('#protection_data').show();
        }
    }

    $(document).ready(function() {
    $('#protection_switch').change(function() {
            protection_selected();
        });
    });
    window.onload = protection_selected;

1 个答案:

答案 0 :(得分:1)

听取重置点击。

function protection_selected() {
    var isVisible = $('#protection_switch').val() == '1';
    $('#protection_data').toggle(isVisible);
}

$(function(){  //document ready
    $("#protection_switch")  //get your select element
        .on("change", protection_selected)  //listen for change event
        .change();  //trigger the change event so defaults can be set
    $('input:reset').on("click", function(e){  //bind click event to reset button 
        this.form.reset();  //force reset so we guarantee it has finished running
        protection_selected();  //run the update code
        e.preventDefault();  //cancel the click since we already ran the reset code
    });
});

关于重置的后方的痛苦是你可以检测它何时被调用,但是在它成功运行之后没有事件。这就是为什么我捕获了点击,在表单上运行重置,称为你的功能,并取消了点击。其他方法是在内部使用延迟而不是调用函数,但这可能导致竞争条件。