这是我在本站的第一篇帖子,希望您能给我留个面子。我正在尝试创建一个HTML/PHP表单,并使用一小段JavaScript在单击按钮时添加额外的行,并为两个字段增加ID。
按钮可以添加行,但似乎无法增加ID,只是使用与上一行相同的ID。希望有人能提供帮助?
按钮可以添加行,但似乎无法增加ID,只是使用与上一行相同的ID。希望有人能提供帮助?
$(window).load(function(){
var table = $('#productanddates')[0];
var newIDSuffix = 2;
$(table).delegate('#button2', 'click', function () {
var thisRow = $(this).closest('tr')[0];
var cloned = $(thisRow).clone();
cloned.find('input, select').each(function () {
var id = $(this).attr('id');
id = id.substring(0, id.length - 1) + newIDSuffix;
$(this).attr('id', id);
});
cloned.insertAfter(thisRow).find('input:date').val('');
newIDSuffix++;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="blue-bar ta-l">
<div class="container">
<h1>Submit Your Insurance Renewal Date(s)</h1>
</div>
</div>
<div class="grey-bar">
<div class="container">
<div class="rounded-box">
<div>
<label for="name">Name</label>
<input type="text" id="name" name="name" autocomplete="off" required />
</div>
<div>
<label for="name">Renewal Dates</label>
</div>
<table width="100%" border="0" cellspacing="0" cellpadding="5" id="productanddates" class="border">
<tr>
<td>
<select name="insurance_type1" id="insurance_type1">
<option></option>
<option>Car</option>
<option>Home</option>
<option>Van</option>
<option>Business</option>
<option>GAP</option>
<option>Travel</option>
</select>
</td>
<td>
<input type="date" name="renewal_date1" id="renewal_date1" />
</td>
<td>
<input type="button" name="button2" id="button2" value="+" />
</td>
</tr>
</table>
<div>
<label for="telephone_number">Contact Number</label>
<input type="tel" id="telephone_number" name="telephone_number" pattern="\d{11}" autocomplete="off" required />
</div>
<div>
<label for="email">Email Address</label>
<input type="email" id="email" name="email" autocomplete="off" required />
</div>
<div>
<input name="submit" type="submit" value="Submit" class="btn">
</div>
</div>
.find('input:date')
更改为.find('input.date')
并在日期输入中添加class="date"
。 - SeannewIDSuffix
的声明放在全局 JavaScript 中而不是$(window).load
函数中吗? - yW0K5oid
属性。不仅将标签与每个输入相关联是最佳实践,通过将标签的for
属性与输入的id
匹配,对于任何类型的可访问性支持(例如屏幕阅读器)来说绝对必要。 - talemyn