Javascript Help

Discussion in 'Web Design and Development' started by Coolnat2004, Dec 8, 2007.

  1. Coolnat2004 macrumors 6502

    Coolnat2004

    Joined:
    Jan 12, 2005
    #1
    I am working on a website where I need multiple input boxes. I want a new box to be formed when a button is clicked. It works fine so far, but whenever a new box is formed, the data inputted in the previous boxes are reset.

    Code:
    <script type="text/javascript">	
    	function addLink() {
    		x = document.getElementById("addl_links");
    		x.innerHTML += '<br /><input type="text" name="addl_links[]" value="http://" size="20" />';
    		reloadBottomBar();
    		return false;
    	}
    </script>
    
    
    ...
    
    
    <tr>
    	<td class="row2 tableLabel">Additional Links</td>
    	<td class="row2">
    		<input type="text" name="addl_links[]" value="http://" size="20" />
    		
    		<span id="addl_links"></span>
    		<br />
    		<input class="button" type="button" value="Add Another Link" onclick="addLink();" style="width: 100%;" />
    	</td>
    </tr>
    
    How can I add to the innerHTML without resetting the input box values?
     
  2. jeremy.king macrumors 603

    jeremy.king

    Joined:
    Jul 23, 2002
    Location:
    Fuquay Varina, NC
    #2
    May want to consider the DOM way...seems to work fine.

    Good Luck

    PS. Instead of <br>, consider using CSS to space these.

    Code:
    	<script type="text/javascript">	
    		function addLink() {
    			x = document.getElementById("theLinks");
    			var input = document.createElement("input");
    			input.name = "addl_links[]";
    			input.type = "text";
    			input.value="http://";
    			x.appendChild(input);
    			return false;
    		}
    	</script>
    
    
    <table>
    	<tr>
    		<td class="row2 tableLabel">Additional Links</td>
    		<td class="row2">
    			<span id="theLinks">
    			<input type="text" name="addl_links[]" value="http://" size="20" />
    			<br />
    			</span>
    			
    			<input class="button" type="button" value="Add Another Link" onclick="addLink();" style="width: 100%;" />
    		</td>
    	</tr>
    </table>
    
     
  3. Coolnat2004 thread starter macrumors 6502

    Coolnat2004

    Joined:
    Jan 12, 2005
    #3
    Awesome, thank you! I am kind of playing this Javascript stuff by ear.
     
  4. bhess macrumors newbie

    Joined:
    Nov 8, 2007
    #4
    For the record, the reason that the input boxes kept resetting themselves is that
    Code:
    x.innerHTML += (Code)
    is basically a shorthand way of writing
    Code:
    x.innerHTML = x.innerHTML + (Code)
    so all the input fields were created anew, rather than just one being added, if that makes any sense.
     

Share This Page