I am currently using this code to add and delete input fields when necessary but would like to update the placeholder tag when I delete a box. I have included the source for the page to show the functions and any help is greatly appreciated before hand. Thanks!
<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>
You need to add one more line to change the input placeholder
in your .each
loop.
$(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
});
});
check this Fiddle
Instead of
$(this).html("Address " + ($(this).parents('.address').index() + 1));
You should do this
$(this).attr("placeholder", "Address " + ($(this).parents('.address').index() + 1));
Remember, placeholder
is an attribute of the input tag, not the html content of it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.