Reputation:
I am attempting to create an appear and disappear effect with an input. When the radio button is "no", the item should appear. When the radio button is "yes", the item should disappear. I have got the item to appear so far, but cannot get it to be removed through DOM. I have included my example on how I can remove my email which i commented out, but can't seem to remove the innerHTML or the input.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
function myFunction() {
var label = document.createElement("label");
label.innerHTML = "<br>Shipment Cost : $";
var x = document.createElement("INPUT");
x.setAttribute("type", "text");
var sp2 = document.getElementById("emailP");
var parentDiv = sp2.parentNode;
parentDiv.insertBefore(x, sp2);
parentDiv.insertBefore(label, x);
alert("Added Text Box");
}
function myFunction2() {
alert("Removed Textbox and Input");
anchor = document.getElementById("label");
anchor.parentNode.removeChild(anchor);
anchor2 = document.getElementById("INPUT");
anchor2.parentNode.removeChild(anchor2);
//THIS WORKS TO REMOVE EMAIL.
//anchor3 = document.getElementById("emailP");
//anchor3.parentNode.removeChild(anchor3);
}
</script>
<form action="#" method="post" onsubmit="alert('Your form has been submitted.'); return false;">
<p class="boldParagraph" id="tip3P">Shipping costs are free:</p>
<input type="radio" name="tip3" value="3" onclick="myFunction2()" />Yes
<input type="radio" name="tip3" value="4" onclick="myFunction(); this.onclick=null;" />No
<p class="boldParagraph" id="emailP">Email of seller:</p>
<input class="averageTextBox" type="email" id="emailAddress" value="" required>
<br>
<br>
<button>Submit</button>
</form>
</body>
</html>
Upvotes: 1
Views: 71
Reputation: 2401
It's not working, because the lines anchor = document.getElementById("label");
and anchor2 = document.getElementById("INPUT");
are looking for elements with the id label
and input
, but can't find them. Those are actually tag names.
You need to add an id to the elements you create in the first function:
label.setAttribute("id", "idForLabel");
x.setAttribute("id", "idForInput");
and then change the lines in the second function to:
anchor = document.getElementById("idForLabel");
anchor2 = document.getElementById("idForInput");
Upvotes: 2