[英]Combine post data before sending
我有一個表格,可以在其中填寫多個字段。 字段的數量不是固定的,而是取決於用戶的輸入。
簡化形式:
<form method="POST" action="post.php">
Field one: <input type="text" name="field[]" /><br />
Field two: <input type="text" name="field[]" /><br />
Field three: <input type="text" name="field[]" /><br />
<br /><br />
Checkbox one: <input type="checkbox" name="check[]" value="1" /><br />
Checkbox two: <input type="checkbox" name="check[]" value="1" /><br />
Checkbox three: <input type="checkbox" name="check[]" value="1" /><br />
<br /><br />
<input type="submit" value="Submit" />
</form>
我面臨的問題是, field one
應該與checkbox one
配對, two
與two
配對,依此類推。 這聽起來很難,對嗎? 如果檢查並填寫了所有內容,則不是:
Array
(
[field] => Array
(
[0] => one
[1] => two
[2] => three
)
[check] => Array
(
[0] => 1
[1] => 1
[2] => 1
)
)
在PHP中,我可以將數組索引鏈接在一起,一切都很好。 我面臨的問題是當您不選擇第二個復選框時。 如果這樣做,則check post data
中的條目將少一個:
Array
(
[field] => Array
(
[0] => one
[1] => two
[2] => three
)
[check] => Array
(
[0] => 1
[1] => 1
)
)
處理這種情況的最佳方法是什么? 不能選擇Ajax提交,但是可以使用JavaScript。
我在想某種方法可以在JS中為每個元素(一個,兩個,三個)創建數組並提交該數據。 問題是,我應該怎么做,還是有更好的(更精細)的方法來解決這個問題?
您需要將它們與匹配的索引配對,並在定義它之前為復選框設置默認的隱藏輸入:
Field one: <input type="text" name="field[0]" /><br />
<input type="hidden" name="check[0]" value="0">
Checkbox one: <input type="checkbox" name="check[0]" value="1" /><br />
因此,現在您總是有一個check[0]
與field[0]
check[0]
匹配,但是如果未選中,它將具有值0
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.