我正在嘗試爲我的婚禮設置一個RSVP表單,因此您可以一次爲多個客人克隆幾個字段以回覆(http://adrianandemma.com/)。這些克隆的字段包括幾個單選按鈕,用於'參加是/否'。我試圖從name =「coming [0]」將name屬性增加到name =「coming [1]」,name =「coming [2]」,name =「 [3]「等。如何使用jQuery在克隆的輸入上增加名稱attrVal數組?
我需要嘗試這樣做,因爲每個克隆的單選按鈕都需要具有唯一的名稱屬性,否則您無法一次選擇多個」是/否「答案。這意味着我不能只使用一個空的數組名=「coming []」。
我想我是部分存在的,因爲當我克隆字段在目前我的JS正在修改每個克隆字段name =「coming [0] [1]」,name =「coming [0] [2] 「,name =」coming [0] [3]「。
我只需要嘗試去除[0],但不能解決如何使用jQuery來做到這一點。
這裏是我的HTML表單:
<form action="?" method="post">
<?php if(@$errors) :?>
<p class="errors"><?php echo $errors; ?></p>
<?php endif; ?>
<input type="hidden" name="submit" value="1" />
<div class="form-row">
<div class="field-l">
<p>Name</p>
</div>
<div class="field-r">
<p>Attending?</p>
</div>
</div>
<div class="form-row guest">
<div class="field-l">
<input type="text" name="name[0]" id="name" value="<?php echo htmlspecialchars(@$_REQUEST['name']); ?>" tabindex="1" />
</div>
<div class="field-r">
<input type="radio" name="coming[0]" id="coming-yes" class="coming-yes" value="Yes"><label for="coming-yes">Yes</label><input type="radio" name="coming[0]" id="coming-no" class="coming-no" value="No"><label for="coming-no">No</label>
</div>
</div>
<a class="addguest" href="#">Add further guest</a>
<div class="form-row">
<button type="submit" id="rsvp-submit" tabindex="2">Submit RSVP</button>
</div>
</form>
,這裏是我的jQuery:
$(document).ready(function() {
$('.addguest').on('click', function(e) {
e.preventDefault();
//
// get the current number of ele and increment it
//
var i = $('.guest').length + 1;
$('.guest').first().clone().find("input").attr('id', function(idx, attrVal) {
return attrVal + i; // change the id
}).attr('name', function(idx, attrVal) {
return attrVal+'['+i+']'; // change the name
}).val('').removeAttr('checked').end().find('label').attr('for', function(idx, attrVal) {
return attrVal + i; // change the for
}).end().insertBefore(this);
});
});
這裏是我似乎並不通過單選按鈕值來拉動型的方法代碼:
<?php
$name = $_POST['name'];
$coming = $_POST['coming'];
$errors = "";
if([email protected]$_POST['name']) { $errors .= "Please enter your name.<br/>\n"; }
if([email protected]$_POST['coming']) { $errors .= "Please enter yes or no for attending.<br/>\n"; }
if(@$_POST['emailaddress'] != '') { $spam = '1'; }
if (!$errors && @$spam != '1')
{
$to = "[email protected]";
$subject = "Wedding RSVP";
$headers = "From: [email protected]";
$body = "The following RSVP has been sent via the website.\n\n";
for($i=0; $i < count($_POST['name']); $i++) {
$body .= "
Name ".($i+1)." : " . $_POST['name'][$i] . "\n
Coming ".($i+1)." : " . $_POST['coming'][$i] ."\n\n";
}
$body .= "\n\nDate Received: " . date("j F Y, g:i a") . "\n";
mail($to,$subject,$body,$headers);
}
?>
我認爲你會得到更多的答案,如果你能打破這成最小的問題。例如,你不需要顯示你的PHP後端,因爲你的問題在代碼的那一部分之前。 – styfle
在從名稱中添加''['+ i +']''刪除'[0]''之前。 – siddiq
感謝@styfle我已經從我的問題中刪除了它。 – ade123