最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Add input to form using JS - Stack Overflow

programmeradmin7浏览0评论

It's possible to add inputs that are created dynamically by the user to a form?

Let's say I have this when the page loads:

<form id="my-form" xl-form>
... // here the inputs
</form>

And after that, I create an input (after the page loads)

<input type="input" class="integr_elements" placeholder="name" id="name">

How can I add it inside the form that has "my-form" as id? I need to add it inside because i want to use a GitHub plugin that will affect only the inputs that are inside the form.

Is this possible?

Thanks!

PS: Before posting this, searched on the forum but found 2013 post and seems there are some deprecated ways.

It's possible to add inputs that are created dynamically by the user to a form?

Let's say I have this when the page loads:

<form id="my-form" xl-form>
... // here the inputs
</form>

And after that, I create an input (after the page loads)

<input type="input" class="integr_elements" placeholder="name" id="name">

How can I add it inside the form that has "my-form" as id? I need to add it inside because i want to use a GitHub plugin that will affect only the inputs that are inside the form.

Is this possible?

Thanks!

PS: Before posting this, searched on the forum but found 2013 post and seems there are some deprecated ways.

Share asked Jul 15, 2018 at 23:45 K3ny1K3ny1 711 gold badge1 silver badge7 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 8

You can use Node.appendChild() for a pure javascript solution (no jQuery).

const el = document.createElement("input");
el.className = "integr_elements";
el.placeholder = "name";
el.id = "name";

const form = document.getElementById("my-form");
form.appendChild(el);
<form id="my-form" xl-form></form>

$('#my-form').append('<input type="input" class="integr_elements" placeholder="name" id="name">');

Something like this? Simply attaching or appending html content onto the form field and so on, you can change the values, names, types or even input types!

$(document).ready(function(){
  $("#myForm").append("<input name='entry1' type='text'></input>");
  $("#myForm").append("<input name='entry2' type='password'></input>");
  $("#myForm").append("<input name='entry3' type='text'></input>");
})
input {
display:block;
margin:5px;
}
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
  
</form>

发布评论

评论列表(0)

  1. 暂无评论