Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

javascript - Add more text fields dynamically in new line (html)

I used code from http://viralpatel.net/blogs/dynamic-add-textbox-input-button-radio-element-html-javascript/ html-javascript/ .my code is this:

<HTML>
<HEAD>
<TITLE>Dynamically add Textbox, Radio, Button in html Form using JavaScript</TITLE>
<SCRIPT language="javascript">
function add() {

    for (i=1; i<=5; i++)
      {
????    //Create an input type dynamically.
????    var element = document.createElement("input");
?    
????    //Assign different attributes to the element.
????    element.setAttribute("type", i);
????    element.setAttribute("name", i);
????    element.setAttribute("value", i);
?    
?    
???    ?var foo = document.getElementById("fooBar");
?    
????    //Append the element in page (in span).
????    foo.appendChild(element);
      }

?
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
<H2>Dynamically add element in form.</H2>
Select the element and hit Add to add it in form.
<BR/>
<INPUT type="button" value="Add" onclick="add()"/>
?    
<span id="fooBar">&nbsp;</span>
?    
</FORM>
</BODY>
</HTML>

That code works. But instead of adding it horizontally, I want every new text field added in a new line. I've tried to use </script><br/><script>, <html><br/></html>, document.write(" "), and document.write(" ") in the loop function but it doesnt work like what I want. What should I do?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Why not just do this?

var br = document.createElement("br");
foo.appendChild(br);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...