Javascript 将行添加到 HTML 表和增量 ID

Javascript Add Row to HTML Table & Increment ID

本文关键字:ID HTML 添加 Javascript      更新时间:2023-09-26

这是我在这个网站上的第一篇文章,所以希望你能对我放轻松。我正在尝试创建一个HTML/PHP表单,并在单击按钮时使用一小段Javascript向表添加其他行,并增加两个字段的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>

cloned.insertAfter(thisRow).find('input:date').val('');

此行不正确。它将引发invalid selector错误。

您需要将其更改为:

cloned.insertAfter(thisRow).find('input[type="date"]').val('');

jQuery实际上确实支持选择器中的:INPUT-TYPE format,但不支持新的HTML5输入类型:因此在这里使用input[type="date"]是目前选择具有HTML5类型的元素的正确方法。请注意值周围的引号。如果要选择具有特定值的属性。

CSS选择器的选择器概述在这里:W3schools。

由于此行抛出错误,因此您的newIDSuffix永远不会更新,因为脚本由于脚本错误,脚本在该行之前停止。


@Charlietfl提出了一个关于学习更多关于类和 DOM 遍历的有效观点。但是,这不会修复此代码。或者解释为什么你的代码不起作用。不过,这是一个很好的提示。

我已经尝试了我认为您要完成的更干净的版本。 我将介绍主要更新:

  1. 将按钮idname从"button2"更新为"button1" - 我假设您希望在每行的输入之间保持索引同步。
  2. $(window).load(function() {更改为$("document").ready(function() { - 虽然两者都有效,但前者将等到所有图像完成加载,而后者将在 DOM 完成构建后触发。 除非您真的希望先加载图像,否则我建议您使用 $("document").ready() ,以便更快地触发代码。
  3. 删除[0]引用 - 在 jQuery 选择器集合之后使用 [0] 的主要原因是引用所选 jQuery 元素的 DOM 版本,以便我们对其使用"香草"JavaScript 方法。 在所有情况下,您都在重新调整 $(...) 中的变量,这只会将 DOM 元素转换回 jQuery 对象,因此不需要额外的步骤。
  4. .delegate()方法更改为.on() - 正如 Howard Renollet 所指出的,这是用于现代版本的 jQuery 的正确方法。 请注意,"事件"和"目标"参数已经交换了on中的位置,从它们在delegate的位置。
  5. 将事件目标从 #button2 更改为:button - 这将确保新行中的所有按钮也允许您添加其他行,而不仅仅是第一行。
  6. clone目标从单击的行切换到表中的最后一行 - 这将有助于保持行编号的一致性和升序。 无论单击哪一个行,克隆的行将始终是最后一个行,新行将始终放在其后面。
  7. 更改了索引,以使用最后一行的索引作为新行的基础,并使用正则表达式来确定它 - 现在对表进行排序,您始终可以指望最后一行具有最高的索引。 通过使用正则表达式 /^(.+)('d+)$/i ,您可以将索引值拆分为"索引之前的所有内容"和"索引(即,在值末尾或多个数字上)"。 然后,您只需将索引递增 1 并重新附加它即可获得新值。 使用正则表达式方法还可以让您轻松适应,它曾经超过 9 行(即两位数的索引)。
  8. 更新了每个输入的idname属性 - 我假设您希望每个元素的idname属性都相同,基于初始行,并且您只是更新代码中的id,这会导致发送数据时出现问题。
  9. $("input:date")更改为$("input[type='date']) - 正如Mouser指出的那样,这确实是代码最初失败的核心原因。 所有其他更改将帮助您避免将来出现其他问题,或者只是与"代码质量"相关的更改。

所以。。。这些是主要更新。 :) 如果我误解了您要做什么或您有任何疑问,请告诉我。

$("document").ready(function() {
	$('#productanddates').on('click', ':button', function () {
		var lastRow = $(this).closest('table').find("tr:last-child");
		var cloned = lastRow.clone();
		cloned.find('input, select').each(function () {
			var id = $(this).attr('id');
			
			var regIdMatch = /^(.+)('d+)$/; 
			var aIdParts = id.match(regIdMatch);
			var newId = aIdParts[1] + (parseInt(aIdParts[2], 10) + 1);
			$(this).attr('id', newId);
			$(this).attr('name', newId);
		});
		cloned.find("input[type='date']").val('');
		cloned.insertAfter(lastRow);
	});
});
<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="button1" id="button1" 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>

cloned.insertAfter(thisRow).find('input[type="date"]').val('');