jQuery: On document load check if checkbox is selected and do function
I have few <li>
's with a checkbox on each <li>
which the value of it is saved into a database. On document load, the <li>
's that have the checkbox selected, I want to add a class '.done'.
I tried this:
if (currentTODO.find('.status').is(":checked")) {
currentTODO.find('.text').addClass("done");
alert('Test.');
}
but it works only if it used under click function, mousemove etc but not on document load. Also, If I have that piece of cod开发者_开发技巧e under on Document load, nothing else works.
I hope someone can help me out.
Thanks alot
Something like this:
$('input[type="checkbox"][checked="checked"]').parent().addClass('done');
http://jsfiddle.net/SBMEm/
Edit: This might be closer to what you were trying to do:
$('li').filter(function() {
return $(this).find('input').is(':checked');
}).addClass('done');
http://jsfiddle.net/SBMEm/7/
I have no problem with any of these working on document load.
Edit: Incidentally, as is often the case with a jQuery-based solution, you can just do this in CSS:
input:checked:after {
margin-left: 20px;
content: "Done";
display: block;
}
http://jsfiddle.net/3SRQd/
Unless you're interested in doing something else with it programmatically or need it to actually have the class for some other reason.
Extra edit: How about this? http://jsfiddle.net/EDs3N/12/ (Incidentally, I'm headed home.)
yo need to call your function in here
$(document).ready(function()
{
currentTODO.find('.status').is(":checked")) { //or whatever code yo are using
currentTODO.find('.text').addClass("done");
alert('Test.');
};
Why not runt he check when the document loads
function check_checkbox () {
if (currentTODO.find('.status').is(":checked")) {
currentTODO.find('.text').addClass("done");
alert('Test.');
}
}
$(document).ready(function () {
check_checkbox()
}
or if you define it inside the doc ready which you shouldn't do but if you did
$(document).ready(function () {
function check_checkbox () {
if (currentTODO.find('.status').is(":checked")) {
currentTODO.find('.text').addClass("done");
alert('Test.');
}
}()
}
精彩评论