简体   繁体   中英

Jquery Code to show link while checkbox is checked on initial page load

I have a following piece of code which works fine, when i check or uncheck the checkbox, but when i initially loads my page and some of my checkboxes are already checked, i want to show the div box to be visible but the code is not doing so, am i missing anything

please guide through the following code

Thanks

$(document).ready(function() {
    //check the state of the checkox
    $(".showinvoice").is(':checked') {
        var stats = $(this).attr('data-id');
        $("#"+stats).css('display','block');
    }
    //check the code only when the click button is triggered    
    $(".showinvoice").click(function(e) {
        var getStudent = $(this).attr('data-id');
        if ($(this).is(':checked')) {
            $("#"+getStudent).css('display','block');
        } else {
            $("#"+getStudent).css('display','none');
        }
    });
});

Firstly you're missing the if statement around the .showinvoice state condition.

Secondly you should use the data() method to access data-* attributes. You should also use the change method when dealing with radio and checkbox inputs so that the events are still raised by users who navigate using the keyboard. Lastly you can remove the if statement and just use toggle() instead.

To achieve what you require all you need to do is raise a change event on the checkboxes on load of the page. Try this;

// check the state of the checkox
if ($(".showinvoice").is(':checked')) {
    var stats = $(this).data('id');
    $("#" + stats).show();
}

// check the code only when the click button is triggered    
$(".showinvoice").change(function(e) {
    var getStudent = $(this).data('id');
    $("#" + getStudent).toggle(this.checked);
}).change(); // < to run this code when the page loads

Try changing your first part to...

//check the state of the checkox
$(".showinvoice:checked").each(function() {
    var stats = $(this).data('id');
    $("#"+stats).css('display','block');
});

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