Jquery/JS Show dynamic checkbox input group title if at least one or more are checked and vice versa

Home / Uncategorized / Jquery/JS Show dynamic checkbox input group title if at least one or more are checked and vice versa

Question:
I want to show input group title if at least one checkbox is checked, and hide title if no checkboxes checked. Each group has his own title and data-value. There may be 5+ input groups.
Here is the codepen: [Example code here][1]

[1]: https://codepen.io/anon/pen/JyrQgW

$(document).ready(function(){

}); .output {
margin-top:45px;
}

group1

item1
item2
item3
item4

group2

item1
item2
item3
item4

HERE SHOW TITLES

enter code here

At the end, I’m not so good with JS/Jquery but I was trying to make it work for a few hours and have a feeling that I go very deep but there is a 2 line solution.

Thanks for help


Answer:
I this what you are looking for?
$(document).ready(function() {
check()
});
$("input[type=checkbox]").change(function() {
check()
})

function check() {
$(".group-block").each(function() {
$(this).find(".group-title").css("display", $(this).find("input[type=checkbox]:checked").length ? "block" : "none")
})
}

It will check if any checkbox has been checked on both .ready() and .change() statement, and show or hide the title depends on the result.

$(document).ready(function() {
check()
});
$("input[type=checkbox]").change(function() {
check()
})

function check() {
$(".group-block").each(function() {
$(this).find(".group-title").css("display", $(this).find("input[type=checkbox]:checked").length ? "block" : "none")
})
} .output {
margin-top: 45px;
}

group1

item1
item2
item3
item4

group2

item1
item2
item3
item4

HERE SHOW TITLES

Demo 2 from coment

$(document).ready(function() {
check()
});
$("input[type=checkbox]").change(function() {
check()
})

function check() {
$(".output").text("");
$(".group-title").hide();

$(".group-block").each(function() {
if ($(this).find("input[type=checkbox]:checked").length)
$(".output").text($(".output").text() + $(this).find(".group-title").text())
})
} .output {
margin-top: 45px;
}

group1

item1
item2
item3
item4

group2

item1
item2
item3
item4

HERE SHOW TITLES


Read more

Leave a Reply

Your email address will not be published. Required fields are marked *