I am having a difficulty when trying to make an if-statement with $(this).attr("id"). Want I want is that when a checkbox is clicked AND checked, its ID is logged in a div #log (this works). When it is clicked and not checked, jQuery should check whether a logged line is the same as the ID of the checkbox. If so, that span should get removed.
Here is a jsfiddle: http://jsfiddle.net/fLskG/1/
So when you click Option 1 the text option-0 will appear (this is the checkbox’s ID). When you click the button again, that text should disappear.
Here is the script:
$(document).ready(function() {
$(".menu").find("input:checkbox").click(function() {
if ($(this).is(":checked")) {
$("#textValue").text($(this).val());
$("#log").append("<span>" + this.id + "</span><br/>");
}
else {
if ($("#log").children("span").contains($(this).attr("id"))) {
console.log($(this).attr("id"));
$("#log").children("span").remove();
}
}
});
});
I am quite sure the problem lies with the ‘contains’. But I don’t know how to make jQuery check whether there is a span which contains the ID of the checkbox checked in the first function.
Thanks.
You could adopt the HTML5 data attribute, but since it’s one-to-one, I just went with giving the span an id of
log-{checkbox-id}, so basically:Here’s the fiddle: http://jsfiddle.net/crazytonyi/fLskG/7/
The nice thing with this is that you don’t have to confirm if the value already is in the list, since it just won’t be found with the selector. I would probably tighten up how you did the insert and HTML as well, but for now, I just wanted to modify the code enough to show the id tag solution.
Here it is, a bit tightened up:
Notice that the log is now a
ulso no need for a break, etc, making it easier to add the id attribute and text. New demo at: http://jsfiddle.net/crazytonyi/fLskG/12/