Page 1 of 1

.hide() and .show() with .append()

Posted: Wed Jun 30, 2010 5:12 am
by wasir
I am using 2 divs inside a form:
<div id=one>consists of a text field and a checkbox</div>
<div id=two>consists of another text field</div>

<div id=two> is always hidden. I am also using a button at the end to repeat (append) these 2 divs.

I want <div id=two> to show only when the checkbox in <div id=one> is checked and hide when the checkbox in <div id=one> is unchecked. The textfield and check names are array.

Is this possible?

Code: Select all

 <head>
       <script type="text/javascript">
             $(document).ready(function() {
                   $("#addTestAppend").click(function() {
                         $("#testAppend").append(
                               "<div id=one>"
                                     +"<input type=\"text\" name=\"name[]\" /><br />"
                                     +"<input type=\"checkbox\" name=\"needDivTwo[]\" id=\"needDivTwo\" />"
                               +"</div>"
                               +"<div id=two>"
                                     +"<input type=\"text\" name=\"age[]\" />"
                               +"</div>"
                         );
                   });
             });
       </script>
 </head>
 <body>
       <form name="name" method="post" action="">
             <div id=testAppend>
                   <div id=one>
                         <input type="text" name="name[]" /><br />
                         <input type="checkbox" name="needDivTwo[]" id="needDivTwo" />
                   </div>
                   <div id=two>
                         <input type="text" name="age[]" />
                   </div>
             </div>
             <input type="button" id="addTestAppend" value="[ Add Append ]"  />
       </form>
 </body>

Re: .hide() and .show() with .append()

Posted: Wed Jun 30, 2010 5:38 am
by Eran
Add a click event to the checkbox that will toggle the visibility of the 2nd div. By the way, you are missing quotes around the id attribute, it should be the same as any other attribute.
Also, please note that the id attribute is unique - you cannot have two elements in the same page with the same id attribute, which happens every time you add more elements with the id 'one' and 'two'. Use the class attribute instead.

Re: .hide() and .show() with .append()

Posted: Wed Jun 30, 2010 8:06 pm
by wasir
Thanks Pytrin