Reputation: 1229
I have a checkbox. When it is checked, a paragraph appears. When it is unchecked, it hides. There is no problem about it. What the problem is: if I check the checkbox, when I press F5(refresh) button, checkbox is still checked but paragraph is hided. I want to make paragraph appear when I refresh page.
Here is HTML:
<input type="checkbox" id="something">
<p id="info" style="display:none">Yes ,checkbox is checked now...</p>
Here is Jquery :
$(document).ready(function() {
$("#something").change( function(){
if( $(this).is(':checked') ) {
$("#info").show();
} else {
$("#info").hide();
}
});
});
Upvotes: 2
Views: 5672
Reputation: 11
$(window).bind("beforeunload", function(){
$("#something >#info").show();
});
Upvotes: 0
Reputation: 144689
Just trigger the change event.
$(document).ready(function() {
$("#something").change(function(){
$("#info").toggle(this.checked);
}).change()
})
Upvotes: 1
Reputation: 4376
Your current behavior is because you have the event handler for change. So when you do F5 and refresh, even though it is checked, there is no change.
You can just call this function explicitly in document.ready
function SetParagraphStatus() {
if ($(this).is(':checked')) {
$("#info").show();
} else {
$("#info").hide();
}
}
$(document).ready(function () {
$("#something").change(SetParagraphStatus);
// call it anyway for load.
SetParagraphStatus();
});
Upvotes: 1
Reputation: 75083
You just have to trigger the event
$(document).ready(function() {
// this only runs upon the event
$("#something").change( function(){
if( $(this).is(':checked') ) {
$("#info").show();
} else {
$("#info").hide();
}
});
// trigger the event
$("#something").trigger("change");
});
Upvotes: 2
Reputation: 382150
You should check the state of the checkbox at loading :
$(document).ready(function() {
function f() {
if( $('#something').is(':checked') ) {
$("#info").show();
} else {
$("#info").hide();
}
}
$("#something").change(f);
f();
});
Upvotes: 3