views:

122

answers:

4

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?

+1  A: 

Why don't you add <div id="subdiv"></div> in your HTML and just hide/show this div when you need it?

Soufiane Hassou
+1 for agreement for if it is only visually changed.
thephpdeveloper
I need to add it dynamically and i will store it in the database for further usage of my application
Prasad
A: 
function myToggle() {
  if($("#mycheck:checked").val()!=null) {
    //check is true
    $("#maindiv").append("<div id='subdiv'></div>");
  }
  else {
    //check is false
    $("#subdiv").remove();
  }
}
tommaso
i need to check exists before appending the html...
Prasad
By construction, it won't exist. It is removed when the box is unselected.
Mark Byers
if($("#maindiv").html().index°("<div id='subdiv'>....")!=-1) { maindiv contain subdiv }
tommaso
+2  A: 

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.

Colour Blend
+1 as it should work, but I don't think the checkbox was meant to be inside the `maindiv` and if there are multiple entries, it might be better to use `data('sex')` instead of `data('added')`
fudgey
@fudgey: Yeah, your right. I didn't give naming much taught. I'll make some changes.
Colour Blend
Also the answer from @mtyaka worked for me by checking the length of the element.
Prasad
A: 
$('#my-checkbox').change(function() {
  if ($(this).is(':checked')) {
    if (!$('#subdiv').length) {
      $('#maindiv').append('<div id="subdiv">...</div>');
    }
  } else {
    $('#subdiv').remove();
  }
});
mtyaka