View Full Version : Resolved New fields in a form - can I have some1 taking a look at this code? :)

10-14-2008, 08:35 PM
I'm developing a simple shop-website for a friend of mine, I got the basics covered and now I need to have the "buy"-form functional.

The idea is to have the customer fill in name/address etcetera, in this form I'd also like them to be able to fill in article number and how many of the article they want to buy. Rather then giving them like 5 rows of these fields I figured I'd use a java script to add a new row whenever they click a button should they find themselves with to few fields.

I googled ahead and found this which I thought could do the trick:

When adjusted to my liking I get this code:

<script type="text/javascript">

/* Script from http://www.quirksmode.org/dom/domform.html */

var counter = 0;

function moreFields() {
var newFields = document.getElementById('readroot').cloneNode(true);
newFields.id = '';
newFields.style.display = 'block';
var newField = newFields.childNodes;
for (var i=0;i<newField.length;i++) {
var theName = newField[i].name
if (theName)
newField[i].name = theName + counter;
var insertHere = document.getElementById('writeroot');

window.onload = moreFields;

<div id="readroot" style="display: none">

<table width="400" border="0" cellpadding="0" cellspacing="0">
<td>Artikelnr: </td>
<input type="text" name="artnr" id="artnr">
<td>Antal: </td>
<input name="antal" type="text" id="antal" value="1" size="6">


<form method="post" action="bestall.php">

<span id="writeroot"></span>

<input type="button" id="moreFields" value="Lägg till fler produkter" />

/*the rest of the form, address and stuff which I figured is of no importance atm */


now when I brows the page where this code has been entered I get the first row of article number and the rest of the form - but - when I press the button to add more forms

<input type="button" id="moreFields" value="Lägg till fler produkter" />

nothing happes.

I suspect that since I have no real clue of what I'm doing (I simply copy past stuff) that the problem here might be simple, any way - I'd appreciate if some1 could take a glance at the code to see if I missed something?

Thnx in advance =)

10-15-2008, 01:35 AM
Java!=JavaScript. Moving thread to JavaScript forum.

Philip M
10-15-2008, 08:54 AM
Do not give the button the same name or id as the functon moreFields().

You have not specified any action to take place when the button is clicked.

<input type = "button" id = "mflds" value = "L&#228;gg till fler produkter" onclick = "moreFields()"/>

Prostitutes Appeal to Pope - newspaper headline

10-15-2008, 11:28 AM
thnx for the help I also had to move the button outside my form to get it to work, now I can dynamically create more fields, however, they are having the same name all of them which makes this useless for ordering stuff...

I've given it a second thought and decided to scrap js for now - still appreciate your help ;)