简体   繁体   中英

JavaScript function not being called when trying to hide/unhide a div

I have the following JavaScript code in its own .js file, which is attempting to hide/unhide the div with class "mailing-address-controls" depending on whether or not the "mailing-address-checkbox" is checked. I'd like this to happen on page load & if the check box value is changed:

$(document).ready(() => {

    function mailingAddressCheckbox() {
        if ($(this).is(":checked"))
            $(".mailing-address-controls").addClass("hidden");
        else
            $(".mailing-address-controls").removeClass("hidden");
    }

    $(".mailing-address-checkbox").load(mailingAddressCheckbox);
    $(".mailing-address-checkbox").change(mailingAddressCheckbox);
});

And I have the following Razor .cshtml code that defines the "mailing-address-checkbox" and the "mailing-address-controls":

<label class="control">
    @Html.CheckBoxFor(model => model.IsMailingSameAsPhysical, new { @class = "mailing-address-checkbox" })
    @Html.LabelFor(model => model.IsMailingSameAsPhysical)
</label>
<div class="mailing-address-controls df fww cols hidden">
    ......
</div>

However, the mailingAddressCheckbox function seems to never be called, and nothing happens when I check/uncheck the checkbox. What am I doing wrong please?

jQuery .load() is not an event listener per say, but rather a function to load remote content within the page.

There's not really any similar event that you could use directly on the element... perhaps a .ready() could do the job if you really need that kind of event to trigger your function.

EDIT

To trigger the function on page load while keeping it the way to coded it, you could simply trigger a change event on the desired checkbox: $(".mailing-address-checkbox").trigger("change");

Include the line right after this line and it should work as intended:

$(".mailing-address-checkbox").change(mailingAddressCheckbox);

Triggering the change event won't change the value, but will execute the fonction your associated with the event. You can read more about it in the jQuery 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