我目前正在使用此代码在必要时添加和删除输入字段,但是在删除框时想要更新占位符标记。我已经包含了页面的来源以显示功能,并且非常感谢任何帮助。谢谢!
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(document).ready(function(){
$("#add-address").click(function(e){
e.preventDefault();
var numberOfAddresses = $("#form1").find("input[name^='data[address]']").length;
var label = '<label for="data[address][' + numberOfAddresses + ']">Address ' + (numberOfAddresses + 1) + '</label> ';
var input = '<input type="text" name="data[address][' + numberOfAddresses + ']" id="data[address][' + numberOfAddresses + ']" placeholder= "Address ' + (numberOfAddresses+1) + '"/>';
var removeButton = '<button class="remove-address">Remove</button>';
var html = "<div class='address'>" + label + input + removeButton + "</div>";
$("#form1").find("#add-address").before(html);
});
});
$(document).on("click", ".remove-address",function(e){
e.preventDefault();
$(this).parents(".address").remove();
//update labels
$("#form1").find("label[for^='data[address]']").each(function(){
$(this).html("Address " + ($(this).parents('.address').index() + 1));
});
});
});//]]>
</script>
</head>
<body>
<form id="form1" method="post" action = "h.php">
<div class="address">
<label for="data[address][0]">Address 1</label>
<input type="text" name="data[address][0]" id="data[address][0]" placeholder = "Address 1" />
</div>
<button id="add-address">Add address</button>
<br />
<input type="submit" value="Submit" />
</form>
</body>
答案 0 :(得分:1)
您需要再添加一行来更改placeholder
循环中的输入.each
。
$(document).on("click", ".remove-address",function(e){
e.preventDefault();
$(this).parents(".address").remove();
//update labels
$("#form1").find("label[for^='data[address]']").each(function(){
$(this).html("Address " + ($(this).parents('.address').index() + 1));
$(this).next("input").attr("placeholder","Address " + ($(this).parents('.address').index() + 1)); //new line added
});
});
检查此 Fiddle
答案 1 :(得分:1)
而不是
$(this).html("Address " + ($(this).parents('.address').index() + 1));
你应该这样做
$(this).attr("placeholder", "Address " + ($(this).parents('.address').index() + 1));
请记住,placeholder
是输入标记的属性,而不是输入标记的html内容。