Reputation: 121
I had created a form field that can be added, but I can not remove it. Not sure why it is not working, I think maybe I am passing in the wrong parameters? I have tried many variations.
<h3 class="color-text">What key fatures are you looking for?</h3>
<p class="contact-message">
<textarea id="client-needs" placeholder="What key features are you looking to have within your website? ie. storefront, social media intigrtion, a blogging platform, content managment system, ect." name="client-needs" rows="5" cols="10"></textarea>
</p>
<script type="text/javascript">
var i = 1;
function addUrl(){
if (i<3) {
i++;
var p = document.createElement('p');
p.innerHTML = '<hr><textarea id="client-needs" placeholder="Add URL #'+i+'" name="client-needs'+i+'" rows="1" cols="10"></textarea><input type="button" value="Remove added URL" onclick="removeUrl(this)">';
document.getElementById('examples').appendChild(p);
}
}
function removeUrl(textarea){
document.getElementById('client-needs').removeChild(textarea.parentNode);
i--;
}
</script>
<h3 class="color-text">Do you have and examples of what you want?</h3>
<p class="contact-message" id="examples">
<textarea id="examples" placeholder="Do you know of any website like the one you want? ie. google.com, p5services.com, youtube.com" name="examples" rows="1" cols="10"></textarea>
</p>
<br>
<input type="button" value="Add url example" onclick="addUrl()">
Upvotes: 2
Views: 683
Reputation: 2014
id is unique value for each element you got to much same name ID
var i = 1;
function addUrl(){
if (i<3) {
i++;
var p = document.createElement('p');
p.innerHTML = '<hr><textarea id="client-needs'+i+'" placeholder="Add URL #'+i+'" name="client-needs'+i+'" rows="1" cols="10"></textarea><input type="button" value="Remove added URL" onclick="removeUrl('+i+')">';
document.getElementById('examples').appendChild(p);
}
}
function removeUrl(id){
document.getElementById("client-needs"+id).remove();
i--;
}
Upvotes: 1
Reputation: 193261
Usage of removeChild
is incorrect. To remove added paragrapg with content you should do somethong like this:
function removeUrl(textarea) {
textarea.parentNode.parentNode.removeChild(textarea.parentNode);
i--;
}
textarea.parentNode
is a p
element to be removed, and textarea.parentNode.parentNode
is the parent of this paragraph whatever it is. removeChild
should be called on the parent and it takes a child of the parent to remove.
Upvotes: 2