[英]Dynamically added input's value not being captured in Php
我有一個表單,其中我使用jQuery動態添加輸入字段,然后使用Laravel Php提交該表單的值
我的html:
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div>
<input type="text" name="mytext[]">
</div>
</div>
我的劇本:
<script type="">
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="remove_field">Remove</a></div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
</script>
問題在於,當我提交在輸入框中輸入的值並嘗試使用以下Laravel代碼捕獲它們時。
$mytext =Request::get('mytext');
dd($mytext);
無論我添加了多少文本輸入,都只會捕獲我在html中定義的輸入的第一個值。
輸出:
array:1 [▼
0 => "Text box 1"
]
我該如何解決? 謝謝
您可以為添加的每個輸入添加不同的名稱。
您的HTML:
<input type="text" name="mytext[text]">
您的JS:
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
$(wrapper).append('<div><input type="text" name="mytext[text'+ x++ +']"/><a href="#" class="remove_field">Remove</a></div>'); //add input box
}
});
輸出將是:
"mytext" => array:4 [▼
"text" => "Text"
"text1" => "Text1"
"text2" => "Text2"
"text3" => "Text3"
]
希望對您有所幫助!
您已經有一個變量來計算附加的輸入...
用它!
注意name="mytext'+x+'"
:
$(wrapper).append('<div><input type="text" name="mytext'+x+'"/><a href="#" class="remove_field">Remove</a></div>');
並且還發送了x
來知道發送了多少。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.