0

This is my JS code :

<script language="javascript">
function addInput() {
    document.getElementById('text').innerHTML += "<input type='text' value='' name='a1[]' size='60' />";
    document.getElementById('text').innerHTML += "<input type='text' value='' name='a2[]' size='9' /><br />";
}

function addInput1() {
    document.getElementById('text1').innerHTML += "<input type='text' value='' name='b[]' size='30' /><br />";
}

function addInput2() {
    document.getElementById('text2').innerHTML += "<input type='text' value='' name='c[]' size='30' />
}
</script>

This is my PHP form codes :

<form method="post" enctype="multipart/form-data" name="form1" >


<input type="submit" onclick="addInput()" name="add" value="Add Other" />
<div id="text"></div>

<input type="submit" onclick="addInput1()" name="add1" value="Add Other" />
<div id="text1"></div>

<input type="submit" onclick="addInput2()" name="add2" value="Add Other" />
<div id="text2"></div>

<input type="submit" name="submit" value="Submit" />
</form>

When I add the fields, it works perfectly, but when I try to edit the field, the page resets and all the added fields disappear.

Are there any problems with my JS code? Is there any other way to do this?

1
  • Off topic, but elem.innerHTML += "...new content..." is very destructive. While there may be some cases where it doesn't make much difference, I would suggest avoiding this practice. In your case, it'll erase the values of the inputs that are being destroyed. Commented Mar 2, 2013 at 16:22

2 Answers 2

2

You're using submit buttons to add inputs, but submit buttons submits the form better to use button inputs e.g.

<input type="button">
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for the answer :D. Didn't thought it would be very simple. :D . Really appreciate your help :D
0

Submits buttons are for submitting the form. It's better to use buttons, but also returning false will stop default behaviour of the button. Ex:

function addInput() {
  // your code
  return false;
}

and on the html:

<input type="submit" onclick="return addInput()" name="add" value="Add Other" />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.