check not contains in div html
-
21-09-2019 - |
Question
I have a div <div id="maindiv"></div>
and some checkboxes to add some html element inside that maindiv.
When i check that checkbox, i need to append <div id="subdiv"></div>
after checking that it doesn't contains that element. The subdiv id will vary according to the checkbox selected.
When i uncheck the checkbox, i need to remove the <div id="subdiv"></div>
if exists.
How can i do it using jquery?
Solution
Try this:
$(function() {
var chk = "<input id=\"sex\" name=\"sex\" type=\"checkbox\">";
var sub = "<div id=\"subdiv\">hello</div>";
$("#container").prepend(chk);
$("#sex").click(function(event) {
if ($("#maindiv").data('sex')) {
$("#maindiv").data('sex', false);
$("#subdiv").remove();
} else {
$("#maindiv").data('sex', true);
$("#maindiv").append(sub);
}
});
});
HTML:
<div id="container">
<div id="maindiv">main</div>
</div>
I used data to do the checking.
OTHER TIPS
Why don't you add <div id="subdiv"></div>
in your HTML and just hide/show this div when you need it?
function myToggle() {
if($("#mycheck:checked").val()!=null) {
//check is true
$("#maindiv").append("<div id='subdiv'></div>");
}
else {
//check is false
$("#subdiv").remove();
}
}
$('#my-checkbox').change(function() {
if ($(this).is(':checked')) {
if (!$('#subdiv').length) {
$('#maindiv').append('<div id="subdiv">...</div>');
}
} else {
$('#subdiv').remove();
}
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow