PHP和JQuery添加动态输入

时间:2018-08-02 15:38:45

标签: javascript php jquery arrays

我正在使用Jquery以便在页面上添加动态输入。我只想最初显示一个输入,然后可以通过单击按钮添加更多输入。

这按预期工作。

然后,我使用PHP来捕获输入的$_POST值并将其发送到外部脚本。这也可以,但是我总是在数组中收到一个额外的项目,而且它是空的。

我认为这是因为我的HTML中有一个隐藏的<div>字段,当生成新输入时会显示该字段吗?

我的代码在下面;

HTML

// unnecessary code removed
<div class="after-add-more">
  <button class="add-more" type="button" title="Add"></button>
  <input name="addmore[]" value="" type="text">
</div>

<div class="copy-fields hide">
  <div>
    <button class="remove" type="button" title="Remove"></button>
    <input type="text" name="addmore[]" value="">
  </div>
</div>

JQUERY

$(document).ready(function() {
    //here first get the contents of the div with name class copy-fields and add it to after "after-add-more" div class.
    $(".add-more").click(function() {
        var html = $(".copy-fields").html();
        $(".after-add-more").after(html);
    });
    //here it will remove the current value of the remove button which has been pressed
    $("body").on("click", ".remove", function() {
        $(this).parents(".control-group").remove();
    });
});

PHP

<?php
// unnecessary code removed
$field_values_array = $_POST['addmore'];
?>

我没有生成其他输入,而是在输入框中输入1111111并提交。 print_r($_POST)产生;

[addmore] => Array
    (
        [0] => 1111111
        [1] => 
    )

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您最好获得被单击元素的父元素,然后添加您的标记。这是一个示例:

$(document).ready(function() {

  // this function handles the click event
  function addField(parent) {
    // find your template, in this case its the first .after-add-more
    var html = $(".after-add-more").first().clone();
    // reset the value of any inputs
    $('input', html).val('');
    // wire the click handler for the button
    $("button", html).click(function() {
      addField($(this).parent());
    });
    // append it to the parent of the parent, addContainer
    html.appendTo(parent.parent());
  }

  // wire the click handler for the add-more button
  $(".add-more").click(function() {
    addField($(this).parent());
  });
  
  // I don't know what the intention of this code is so I'm leaving it alone
  $("body").on("click", ".remove", function() {
    $(this).parents(".control-group").remove();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
// unnecessary code removed
<div id="addContainer">
  <div class="after-add-more">
    <button class="add-more" type="button" title="Add">Add</button>
    <input name="addmore[]" value="" type="text">
  </div>
</div>
<div class="copy-fields hide">
  <div>
    <button class="remove" type="button" title="Remove">Remove</button>
    <input type="text" name="addmore[]" value="">
  </div>
</div>