Link to home
Create AccountLog in
Avatar of pnoeric
pnoericFlag for United States of America

asked on

Creating form fields on the fly in JS

Hi, I have a form, and want to dynamically (with JS) add more input fields on the fly.

Here's the HTML and the JS that is supposed to do the insert. I'm getting no error msg, but it's failing. Can anyone tell me what's up?

counter = 0;
function addBrick() {
	var newFields = $('copyme').cloneNode(true);		// make a copy of 'copyme' div
 
	counter++;
	newFields.id = 'newFields' + counter;		// give the copy a unique ID
	newFields.style.display = 'block';
	alert(newFields.id);
 
	var insertHere = $('writehere');			// and insert it onto the page
	insertHere.parentNode.insertBefore(newFields, insertHere);
}
 
 
<a href='javascript: void(0);' onClick='addBrick();'>add brick</a>
 
{* this next div is not shown, but is duplicated to add a field *}
<div id='copyme' style='display: none;'>
	<tr>
		<td style='vertical-align: top;'>label</td>
		<td>
			<select name='another_field[]'> <option>test</option> </select>
		</td>
	</tr>
</div>
{* insert the div here *}
<div id='writehere'></div>		

Open in new window

SOLUTION
Avatar of sledgebox
sledgebox
Flag of United States of America image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Avatar of pnoeric

ASKER


Good catch on the $() thing; I should have said something in my original post... I'm using is Prototype and $() is a helper function that's the same as document.getElementById().

Just to be sure, I went ahead and changed it to document.getElementById(), but it didn't make any difference -- still no results.

It works out of context. I made a blank .html file, put your code in, and it test fine. So, something else on the page is causing the error. Can you share the rest of the markup?
Avatar of pnoeric

ASKER

Hmmm.... that's frustarting :-)

I tried playing with it a bit and discovered that it's failing for me inside the table, but not separate... i.e. if I change the markup to:

            <div id='copyme'>  test text and <input type='text' name='test_field'> </div>
            <div id='writehere'></div>            

Then the JS properly duplicates 'copyme' and makes the new div inside 'writehere'.

...so why would it fail inside a table?
ASKER CERTIFIED SOLUTION
Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account