How do I add textboxes dynamically in Javascript?

2019-01-25 08:09发布

By default I have 5 textboxes. When a user clicks on a button, one textbox should be added.

How could I do this?

7条回答
老娘就宠你
2楼-- · 2019-01-25 08:27
<script>
function add()
{
    document.getElementById("place").innerHTML="<input type='text' value=''>"
}
</script>
<input type="button" value="clickMe" onClick="add();">
<div id="place"></div>
查看更多
smile是对你的礼貌
3楼-- · 2019-01-25 08:42

If you replace the innerHTML, the previously entered values will be cleared, to avoid that, you can append the input elements programmatically:

var input = document.createElement('input'); 
input.type = "text"; 
//...    
container.appendChild(input); 

Check this example.

查看更多
何必那么认真
4楼-- · 2019-01-25 08:42

Javascript Function

function add() {

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

//Create Labels
var label = document.createElement("Label");
label.innerHTML = "New Label";     

//Assign different attributes to the element.
element.setAttribute("type", "text");
element.setAttribute("value", "");
element.setAttribute("name", "Test Name");
element.setAttribute("style", "width:200px");

label.setAttribute("style", "font-weight:normal");

// 'foobar' is the div id, where new fields are to be added
var foo = document.getElementById("fooBar");

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

Html part,

<button id="button" value="Add" onClick:"javascript:add();">

And, Its done!

查看更多
成全新的幸福
5楼-- · 2019-01-25 08:43

Best would be to attach an event on to the onclick of the button, that will set a div's visibility to inline. This is about the best way I can see for this, considering flexibility and robustness.

Have a look here for example code.

查看更多
兄弟一词,经得起流年.
6楼-- · 2019-01-25 08:45
<!DOCTYPE html>
<html>
<body>
 <h1>My First Web Page</h1>
 <p>My first paragraph.</p>
 <button type="button" onclick="myFunction()">Click me!</button>
 <script>
 var count =0;
 function myFunction() {
 count++
  document.write('Lable1');
  document.write('<input type="text" name="one+count">');
  document.write('Lable2');
  document.write('<input type="text" name="two+count">');

  document.write('Lable3'); 
  document.write('<input type="text" name="three+count">');

  document.write('Lable4');
  document.write('<input type="text" name="four+count">');

  document.write(count);

  }
  </script>

  </body>
  </html> 
查看更多
在下西门庆
7楼-- · 2019-01-25 08:48

try this

<html>
<head>
<title>Dynamic Form</title>
<script language="javascript" type="text/javascript" >
function changeIt()
{

createTextbox.innerHTML = createTextbox.innerHTML +"<br><input type='text' name='mytext' >"

}
</script>
</head>
<body>

<form name="form">
<input type="button" value="clickHere" onClick="changeIt()">
<div id="createTextbox"></div>
</form> 
</body>
</html>
查看更多
登录 后发表回答