简体   繁体   中英

Check whether checkbox is checked or not in page load itself by jquery

I have below checkbox and span tag in .Net MVC 3 page,

@Html.CheckBoxFor(m => m.CheckedStatus, new Dictionary<string, object> { { "id", "cbCheckedStatus7" }, { "name", "cbCheckedStatus" }, { "class", "onchange" } })
<span id="spBlueCheckbox" style="display: none; color: blue;"> Some message</span>

Jquery:

jQuery(function ($) {
        $('#cbCheckedStatus7').on('change', function () {            
            $('#spBlueCheckbox').slideToggle(this.checked);
        });

if the checkbox is checked, i need to show the span tag, or else hide it. initially the spab tag is hidden.

I have written jquery to do the above scenario, but it is only working if i click manually by mouse. What i need is, when i navigate from previous page to this page, the checkbox is checked by default based DB flag, but the span tag is not shown.

You can use:

if($('#cbCheckedStatus7').is(':checked')){
   $('#spBlueCheckbox').show();
}

call below jquery on page load :

$(document).ready(function(){
    // do initial check and make show / hide
    if($('#cbCheckedStatus7').is(':checked')){ // check if checkbox checked
       $('#spBlueCheckbox').show();
    }

   // add change handler
   $('#cbCheckedStatus7').on('change', function () {            
       $('#spBlueCheckbox').slideToggle(this.checked);
    });
});

Try this

$(document).ready(function(){
     ($('#cbCheckedStatus7').is(':checked')) ? $('#spBlueCheckbox').show(); : $('#spBlueCheckbox').hide();
})

Edit your code to this :

jQuery(function ($) {
        $('#cbCheckedStatus7').on('change', function () { 
        if(this.checked)           
            $('#spBlueCheckbox').show();//or slide up or down
        else
            $('#spBlueCheckbox').hide();//or slide up or down
        });

and ADD this to end of the page that contains the checkbox

$('#cbCheckedStatus7').change();

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