简体   繁体   中英

Javascript/jQuery: How can I invoke an "onchange()" callback at page load?

I have an ASP.Net Core web form with many groups of input items that can be hidden or displayed, depending on values entered by the user and stored in the database.

This is the callback that "shows" or "hides" submenus whenever a user changes the value in the dropdown menu, it works fine:

$('#DW_Answers_Q430').change(function (e) {
    let a = $('#DW_Answers_Q430').val();
    if (a == "None")
      $('#DW_Q430_grp').css('display','none');
    else $('#DW_Q430_grp').css('display','block');
});

Q: How can I invoke this callback when then "Edit" menu loads, to ensure the submenus are displayed or hidden correctly, depending on the value loaded from the database?

This is what I've tried:

Edit.cshtml:

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    <script type="text/javascript">
        window.onload = function () {
            ...
            dw_refresh();
            ...
        };
    </script>
}

site.js:

function dw_refresh() {
    console.log('dw_refresh()...');   // <-- dw_refresh() gets invoked
    ...
    var a = $('#D_Answers_Q430').val();
    $('#DW_Answers_Q430').val(a).change();  // <-- But the callback never gets invoked
    ...

Q: How can I invoke my callback, to ensure the submenus are displayed correctly when the "Edit" pages first loads?


SOLUTION:

  1. Get rid of dw_refresh()

  2. Substitute bind('load change') :

     $('#DWare_Answers_Q430').bind('load change', function () { let a = $('#DW_Answers_Q430').val(); console.log('DW_Answers_Q430, val:', a); if (a == "None") $('#DW_Q430_grp').css('display','none'); else $('#DW_Q430_grp').css('display','block'); });

In this line:

$('#DW_Answers_Q430').val(a).change();

.change() is an event listener setter that should have a handler function passed in.

To trigger the change event, what you need is:

$('#DW_Answers_Q430').val(a).trigger("change");

Documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM