问题描述:

I would like to add a function that generates multiple fields to my form.

This is how my form looks like:

<form action="form_sent.php" method="post">

<input name="name" type="text" placeholder="Name"><br>

<input name="phone" type="text" placeholder="Phone"><br>

<input name="email" type="text" placeholder="E-Mail"><br><br>

<button>Add more fields</button><br><br>

<input type="submit">

</form>

In my case I want 3 new fields (name, phone, email) when clicking on "Add more fields".

How can I do this?

https://jsfiddle.net/374cxt5s/

网友答案:

Try this: https://jsfiddle.net/Twisty/q8zj00s0/1/

HTML

<form action="form_sent.php" method="post">
  <ul id="fieldList">
    <li>
      <input name="name[]" type="text" placeholder="Name" />
    </li>
    <li>
      <input name="phone[]" type="text" placeholder="Phone" />
    </li>
    <li>
      <input name="email[]" type="text" placeholder="E-Mail">
    </li>
  </ul>
  <button id="addMore">Add more fields</button>
  <br>
  <br>
  <input type="submit">
</form>

CSS

ul {
  padding: 0;
  margin: 0;
}

ul li {
  list-style: none;
}

JQuery

$(function() {
  $("#addMore").click(function(e) {
    e.preventDefault();
    $("#fieldList").append("<li>&nbsp;</li>");
    $("#fieldList").append("<li><input type='text' name='name[]' placeholder='Name' /></li>");
    $("#fieldList").append("<li><input type='text' name='phone[]' placeholder='Phone' /></li>");
    $("#fieldList").append("<li><input type='text' name='email[]' placeholder='E-Mail' /></li>");
  });
});

This allows you to store the results in array when you submit the form. Since you could have 5 names, phones, and emails, an array is the best way to address that. Then in PHP, you would have $_POST['name'][0] as the first one.

网友答案:

It might not be a bad idea to wrap your input fields in a div just so when you append the other inputs they appear consecutively. Try something like this in your html

<form action="form_sent.php" method="post">
 <div id="fields">
   <input name="name" type="text" placeholder="Name"><br>
 <input name="phone" type="text" placeholder="Phone"><br>
 <input name="email" type="text" placeholder="E-Mail"><br><br>
 </div>
 <button>Add more fields</button><br><br>
 <input type="submit">   
</form>

and then your javascript can be completed as so

$(function() {  
$('button').click(function() { addFields(); });
});

function addFields() {
var html = "<input name='name' type='text' placeholder='Name'><br>
 <input name='phone' type='text' placeholder='Phone'><br>
 <input name='email' type='text' placeholder='E-Mail'><br><br>";

 $('#fields').append(html);
}
网友答案:

try something like this :

(function() {
   var button=document.getElementById("add-user");
   button.addEventListener('click', function(event) {
      event.preventDefault();
      var cln = document.getElementsByClassName("user")[0].cloneNode(true);
      document.getElementById("users").insertBefore(cln,this);
      return false;
   });
})();
<form id="users" action="form_sent.php" method="post">
 <div class="user">
   <input name="name" type="text" placeholder="Name"><br>
   <input name="phone" type="text" placeholder="Phone"><br>
   <input name="email" type="text" placeholder="E-Mail"><br><br>
 </div>
   <button id='add-user'>Add more fields</button><br><br>
   <input type="submit">   
</form>
网友答案:

I'm assuming you probably want to create a dynamic form that allows you to add multiple contacts, etc.

CodePen Example

http://codepen.io/anon/pen/yeVRgw

The Basic HTML Setup

So that you can loop through things, and for sake of your own sanity, you'll probably want to segment out each chunk within the form. We'll also set up a hidden input to track how many partitions of name,phone,email have been created. We'll default at 1

<form action="form_sent.php" method="POST">
    <input type="hidden" name="contacts" id="contacts" value="1">

    <div class="form-contacts-container">

        <div class="form-contact" id="form-contact-1">
            <input type="text" name="name-1" id="name-1" placeholder="Name">
            <input type="text" name="email-1" id="email-1" placeholder="E-mail">
            <input type="text" name="phone-1" id="phone-1" placeholder="Phone">
        </div>

        <!-- We'll be adding additional inputs here -->

    </div>

    <div class="form-contacts-add">
        <input type="button" value="Add More Fields" id="add-fields">
    </div>

    <div class="form-contacts-submit">
        <input type="submit" name="submit" id="submit" value="Submit">
    </div>

</form>

The JavaScript

This assumes you are using jQuery, so ensure that this is in your <head>

<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

Now we need to do a few things - firstly, attach an event listener to our button and secondly, add a new <div class="form-contact"> with included fields to our form. We'll also need to ensure that we're counting up to make sure each section has a unique name/id, and we'll increase the hidden input value to count how many contacts have been added in total.

<script type="text/javascript">
    var total = 1; // Our default for how many contacts we have


    $( document ).on( 'click', '#add-fields', function() {

        var addBlockId = total = total + 1;

        var addBlock = document.createElement('div');
        $(addBlock).addClass('form-contact');
        $(addBlock).attr('id','form-contact-' + addBlockId);

        var inputName = document.createElement('input');
        $(inputName).attr('type','text');
        $(inputName).attr('name','name-' + addBlockId);
        $(inputName).attr('id','name-' + addBlockId);
        $(inputName).attr('placeholder','Name');
        $(inputName).appendTo($(addBlock));

        var inputEmail = document.createElement('input');
        $(inputEmail).attr('type','text');
        $(inputEmail).attr('name','email-' + addBlockId);
        $(inputEmail).attr('id','email-' + addBlockId);
        $(inputEmail).attr('placeholder','E-mail');
        $(inputEmail).appendTo($(addBlock));

        var inputPhone = document.createElement('input');
        $(inputPhone).attr('type','text');
        $(inputPhone).attr('name','phone-' + addBlockId);
        $(inputPhone).attr('id','phone-' + addBlockId);
        $(inputPhone).attr('placeholder','Phone');
        $(inputPhone).appendTo($(addBlock));

        $(addBlock).appendTo($('.form-contacts-container'));
        $('#contacts').val(total);

    });

</script>

Processing your Form

The last piece of the puzzle is to process your form properly. Not goign to give you all the answers here, but the basic logic would be to grab the $_POST['contacts'] value we've been updated and run a loop through to grab all of your inputs and associated values. For instance in PHP:

$total = $_POST['contacts'];
$contacts = array();

for( $i = 1; $i < $total; $i++ ) {
    $this_contact = $array(
        'Name'  => $_POST['name-' . $i],
        'Email' => $_POST['email-' . $i],
        'Phone' => $_POST['phone-' . $i]
    );
    array_push($contacts, $this_contact);
}

var_dump( $contacts );
网友答案:

You need to implement jQuery to change the HTMLs DOM.

So, you add this in your <head></head> tags:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>

You need to modify your HTML like this:

<form action="form_sent.php" method="post">
<input name="name" type="text" placeholder="Name"><br>
<input name="phone" type="text" placeholder="Phone"><br>
<input name="email" type="text" placeholder="E-Mail"><br><br>
<button extra="0">Add more fields</button><br><br>
<input type="submit">
</form>

Then you need to use this jQuery code:

<script>
$("button").on("click",function(){
var extra = $(this).attr("extra") + 1;
$("form").append("<input type='text' placeholder='Other Field' name='field' />");
$(this).attr("extra",extra);
}
</script>

This is the end!! :)

网友答案:

Try This : Jquery append() function seems to sort out your answer HTML Code should be as follow :

<form action="form_sent.php" method="post">
   <div class = 'xyz'>
   <input name="name" type="text" placeholder="Name"><br>
   <input name="phone" type="text" placeholder="Phone"><br>
   <input name="email" type="text" placeholder="E-Mail"><br><br>
   </div>
   <button>Add more fields</button><br><br>
   <input type="submit">   
</form>

you JS should be as follow :

$(button).click(function(event){
$('.xyz').append("<input type ='text' class ='name' placeholder = 'Enter name'/><br/>");
$('.xyz').append("<input type='text' class='phone' placeholder='Enter phone'/><br/>");
$('.xyz').append("<input type='mail' class='phone' placeholder='Enter e-mail'/><br/>");
event.preventDefault();
});
网友答案:

This is how I would solve it.

HTML:

<form action="form_sent.php" method="post">
   <div id="inputHolder">
     <input name="name" type="text" placeholder="Name"><br>
     <input name="phone" type="text" placeholder="Phone"><br>
     <input name="email" type="text" placeholder="E-Mail"><br><br>
   </div>

   <button id="addMoreFields">Add more fields</button><br><br>
   <input type="submit">   
</form>

JS:

$( document ).ready(function() {
    $("#addMoreFields").click(function(event) {
        event.preventDefault();

        $("#inputHolder").append('<input name="name" type="text" placeholder="Name"><br>');
        $("#inputHolder").append('<input name="phone" type="text" placeholder="Phone"><br>');
        $("#inputHolder").append('<input name="email" type="text" placeholder="E-Mail"><br><br>');
    });
});

https://jsfiddle.net/r71odb7t/

网友答案:

First you want to clone the elements you want to be adding. Do that when the page loads. Then when the button is clicked, clone the copy and add a copy to the page. And, you could either add type="button" to the button or use e.preventDefault() so your form does not get submitted when the button is clicked.

$(function() {
    var inputs = $('form > button').prev().prev().prevUntil().clone().add('<br><br>');
    $('form > button').on('click', function(e) {  e.preventDefault();  $(this).before(inputs.clone());
    });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="form_sent.php" method="post">
    <input name="name" type="text" placeholder="Name"><br>
   <input name="phone" type="text" placeholder="Phone"><br>
   <input name="email" type="text" placeholder="E-Mail"><br><br>
   <button>Add more fields</button><br><br>
   <input type="submit">   
</form>
相关阅读:
Top