简体   繁体   中英

How to add multiple input field inside a div dynamically using JavaScript/jQuery?

I need to create some multiple input field dynamically on onkeypress event using JavaScript/jQuery.

I have one text-box,when user is entering any key on that text area two input field and second text-box is opening. When user will enter any key on second text box again another two input field and third text-box will open and so on. There is also a cross button is creating to close each individual set of text-box. In my current code I doing this putting all field static as user may create many numbers of input field so that I want to create those in dynamically with different name and id .

My code is in this Plunkr .

EDIT: Misunderstood question, answer below

This can easily be done if you have a specific field in which to create the input fields. For example, I will load input fields into document.body

Everytime you call newinput() an input field is created in parent who's id starts at input0 and increments each time

 var id = 0; var newinput = function() { var parent = document.body var field = document.createElement("input") field.className = "myclassname" field.style = "display:block;" field.id = "input" + id; parent.appendChild(field); id += 1; }
 <body> <div>Click plus to add input</div> <button type="button" name="button" onclick="newinput()">+</button> </body>

In your case, it looks like you want to add a group, you can do this:

var fieldgroup = document.querySelector(".questionshowp .form-group").cloneNode(true); // (1)

var addinput = function(){
    var parent = this.parentNode.parentNode.parentNode; // (2)
    var n = parent.querySelectorAll(".form-control").length 
    var f = fieldgroup.cloneNode(true);
    f.children[0].id = "question"+n // (3)
    f.querySelector(".secondsec").querySelector("button.btn-success").onclick = addinput // (4)
    parent.insertBefore(f,parent.querySelector(".clear")); // (5)
}
  1. Create a copy of a field-group to be used as a template
  2. Get the container of input fields
  3. Set the input field id with regard to total number of form-groups in parent
  4. Make sure template applies addinput() to button
  5. Insert input form before end of parent form

The easiest way apply this function to all + buttons is with JQuery

$("button.btn-sm.btn-success").on("click", addinput)

This would need to be located at the bottom of your html file, and below addinput() definition

EDIT: Real Answer

Turns out I wrote all that and just realized I misunderstood your question. Still we can use the same principle to do what I believe you are asking

master = document.querySelector(".aquestionpart"); // (1)
form = document.querySelector(".questionparts"); // (2)

function show(){
    var f = form.cloneNode(true);
    var n = master.querySelectorAll(".questionparts").length;
    f.id = "questionparts"+(n+1); // (3)
    f.querySelector("#questions").onkeypress = show; // (4)
    this.parentElement.parentElement.querySelector("#questionparts"+ n + " > .questionshowp").style ="display:block;"; // (5)
    this.onkeypress = undefined; // (6)

    master.insertBefore(f,master.children[master.children.length-1]) // (7)
}
form.querySelector("#questions").onkeypress = show; // (8)
form = form.cloneNode(true); // (9)
  1. Get poll container
  2. Get poll question form to use as template
  3. Set new poll question form id with respect to number of others
  4. Set show function to new poll question
  5. Show multiple choice
  6. Make sure subsequent keypresses dont create more questions
  7. Insert question before .clear
  8. sets up first question to show
  9. creates copy of fresh question to use as template

With this your current scripts.js is unnecessary, and .aquestionpart must look like this for proper formatting

<div class="aquestionpart">
    <div class="questionparts" id="questionparts1">...</div>
    <div class="clear"></div>
</div>  

From within .questionparts be sure to remove onkeypress="show();" from input . It should look like this.

<input name="questions" id="questions" class="form-control" placeholder="Questions" value="" type="text">

And finally an interesting note is that both of the scripts I've provided can be used together! (With some slight modifications)

//Author: Shane Mendez
var fieldgroup = document.querySelector(".questionshowp .form-group").cloneNode(true);
var addinput = function(){
    var parent = this.parentNode.parentNode.parentNode;
    var n = parent.querySelectorAll(".form-control").length 
    var f = fieldgroup.cloneNode(true);
    f.children[0].id = "question"+n 
    f.querySelector(".secondsec").querySelector("button.btn-success").onclick = addinput 
    console.log(parent)
    parent.insertBefore(f,parent.children[parent.children.length-1]);
}

master = document.querySelector(".aquestionpart");
form = document.querySelector(".questionparts");

function show(){
    var f = form.cloneNode(true);
    var n = master.querySelectorAll(".questionparts").length;
    f.id = "questionparts"+(n+1);
    f.querySelector("#questions").onkeypress = show;
    console.log(this)
    this.parentElement.parentElement.querySelector("#questionparts"+ n + " > .questionshowp").style ="display:block;";
    this.onkeypress = undefined;
    master.insertBefore(f,master.children[master.children.length-1])
    $(f.querySelectorAll("button.btn-sm.btn-success")).on("click", addinput)
}
form.querySelector("#questions").onkeypress = show;
form = form.cloneNode(true);
$("button.btn-sm.btn-success").on("click", addinput)

If you put this in your scripts.js file and put that at the bottom of your body tag, then the only thing left is the - buttons.

You can use this Press to add multiple input field inside a div dynamically using jQuery. Here you only need to call the function that takes two parameter HTMLElement and config like:

  $(".addInput").click(function() {
    build_inputs($(this), config);
  });

In the config you can add numbers of inputs form config like:

let config = {
  title: "Slides",
  forms: [
    {
      type: "text",
      name: "name",
      class: "form-control mb-2",
      placeholder: "Enter Data..."
    },
    {
      type: "file",
      name: "image",
      class: "btn btn-light btn-sm mb-2 btn-block"
    },
    {
      type: "number",
      name: "mobile",
      class: "form-control mb-2",
      placeholder: "Enter Data..."
    }
  ],
  exportTo:$('#getData')
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM