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

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
wasir
Forum Commoner
Posts: 49
Joined: Sun Jul 08, 2007 11:28 pm

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

Post 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>
User avatar
Eran
DevNet Master
Posts: 3549
Joined: Fri Jan 18, 2008 12:36 am
Location: Israel, ME

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

Post 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.
wasir
Forum Commoner
Posts: 49
Joined: Sun Jul 08, 2007 11:28 pm

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

Post by wasir »

Thanks Pytrin
Post Reply