Question

I am showing and hiding a div based on some options selection.

Have a dropdown list with options 'enabled and disabled'.once user selects enabled needs to display the div else Hide the div.

Based on dropdown option selection Hide/Show div is working fine, but If Disabled is the configured value. when I load the page , div will be hidden(working fine) , Then I will select Enabled, then div shows but ....... When I click on reset option, Dropdown option is getting back to Disabled but Div section which should be hiden is not hiding

Here I have my code like this, protection switch is the wtform field recieved from flask

{{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>

Section should be hide or display

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

Jquery code

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;
Was it helpful?

Solution

Listen for the click on the reset.

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
    });
});

The pain in the rear thing about reset is you can detect when it has called, but there is no event for after it has successfully run. That is why I captured the click, run the reset on the form, called your function, and cancelled the click. Other way is to just use a delay inside and than call the function, but that can lead to a race condition.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top