簡體   English   中英

PHP和JQuery添加動態輸入

[英]PHP & JQuery Adding Dynamic Inputs

我正在使用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] => 
    )

任何幫助表示贊賞。

您可能最好獲取被單擊元素的父級,然后在其后添加標記。 這是一個例子:

 $(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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM