Adding Text Fields..., Need Little Help and Its Important For Me

Discussion in 'jQuery' started by strgraphics, Jun 29, 2011.

  1. #1
    Hello mates...,

    hear is my jQuery code to add text fields dynamically....., its working fine but the problem is for example when i select 3 then 3 fields am getting its coolllll, but again when i select 2 then this time again 2 text fields are adding to the above 3..., how can i fix it

    
    <head>
    
     
      <script type="text/javascript" src="jquery.js"></script>
     
     
     <script type="text/javascript">
     $(document).ready(function(){
    
    		 $('#dropdown').change(function()
    			{
    			
    			  var val = $('#dropdown').val();
    			
                   for(i=0;i<val;i++)
    			   {			    
          
                   $("#tab").append("<tr><td>First Name: </td><td><input type=\"text\" name=fn"+val+"/></td></tr>");
                   $("#tab").append("<tr><td>Last Name: </td><td><input type=\"text\" name=ln"+val+"/></td></tr>");
    
    			   alert('<input type=\"text\" name=\"ln'+val+'"/>'+val);
    			   
                   }  
    
                });
    
      });
    </script>
    </head>
    
    <body>
    <table id="tab">
    
    <tr> <td>test</td> <td><input type="text" name="a"></td> </tr>
    
    </table>
    
    <select id="dropdown" style="border: 1px solid #005e9d;">
       <option selected>--- Please Select ---</option>
       <option value="1">1</option>
       <option value="2">2</option>
       <option value="3">3</option>
       <option value="4">4</option>
       <option value="5">5</option>
       <option value="6">6</option>
       <option value="7">7</option>
       <option value="8">8</option>
     </select>
    
    
    <div id="inputs">
    
    </body>
    
    
    HTML:
     
    strgraphics, Jun 29, 2011 IP
  2. MarPlo

    MarPlo Member

    Messages:
    97
    Likes Received:
    2
    Best Answers:
    2
    Trophy Points:
    48
    #2
    Hy,
    Try add before the for() loop $("#tab").html('');
     
    MarPlo, Jul 2, 2011 IP
  3. LeetPCUser

    LeetPCUser Peon

    Messages:
    711
    Likes Received:
    14
    Best Answers:
    0
    Trophy Points:
    0
    #3
    MarPlo has it right. That line of code will always clear out the tab id before the loop runs, meaning it will clear out all previous data.
     
    LeetPCUser, Jul 8, 2011 IP
  4. strgraphics

    strgraphics Active Member

    Messages:
    710
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    53
    #4
    Hi Leet, thanks lol any way its worked., i used one like of java script to clear..
     
    strgraphics, Jul 11, 2011 IP