1

I found this JavaScript online that adds input buttons when you press a button.

I changed it so that instead of being able to select which type of input you create it just automatically creates a textbox. But it's not working. What should I change?

function add(type) {

  //Create an input type dynamically.
  var element = document.createElement("input");

  //Assign different attributes to the element.
  element.setAttribute("type", "text");
  element.setAttribute("name", "goal[]");

  var foo = document.getElementById("fooBar");

  //Append the element in page (in span).
  foo.appendChild(element);

}

<INPUT type="button" value="Add" onclick="add(document.forms[0].element.value)"/>

<span id="fooBar">&nbsp;</span>

2 Answers 2

1

DEMO

Your add function is correct, but I think something is broken here—document.forms[0].element.value

onclick="add(document.forms[0].element.value)"

Try changing it to

onclick="add()"

Since you're not using that type parameter anyway

Sign up to request clarification or add additional context in comments.

4 Comments

How would I also add a line break after each input so they rendered below each other?
I think you'd want to do: document.createElement("br"); and insert it where you want the line break
Would I put it in the function add()? That didn't work. Should I put it with the onclick along with add?
You should be able to add the br like you did with the input - here's an updated fiddle jsfiddle.net/4Fa8Z/2
0

Some browsers do not allow to set the name attribute dynamically on an element.

You can specify the name attribute in the markup passed to createElement() to work around this problem:

var element = document.createElement("<input name='goal[]' type='text' />");

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.