Theodore Steiner Theodore Steiner - 11 months ago 50
CSS Question

Dynamically Removing Inputs / DOM Error

I've been able to make a section of a form that dynamically adds a tier of inputs on a button click. This new div is appended after the previous div and I am attempting to make a button that can also remove the tier if the user doesn't need it.

My problem is I cannot seem to remove the divs. I can add but not remove. When I look at the DOM I can see when the addDiv button is clicked, it is indeed adding the div and all the content is within the div, so it is being appended properly. But when I try to remove the newly appended div from it's parent element, I get the following error thrown:

addJob.js:18 Uncaught TypeError: Cannot read property 'parentNode' of undefinedremoveJob @ addJob.js:18onclick @ index.html:1

I'm unsure how to make my
function defined in a way that is just the reverse of how it was added.


var i = 0;

function addJob() {

if (i <= 1) {
var div = document.createElement("div");
div.innerHTML = '<input type="text" class="three-lines" name="schoolBoard_' + i + '"> '+
'<input type="text" class="three-lines" name="position_' + i + '"> '+
'<input type="text" class="three-lines" name="years_' + i + '">'+
'<input type="button" value="-" onclick="removeJob()">';


function removeJob(div) {

button {
height: 20px;
width: 20px;
background: none;
margin-left: 10px;
margin-top: 30px;
margin-bottom: 25px;
input[type="button"] {
height: 20px;
width: 20px;
background: none;
border: 1px solid #ccc;
outline: none;
margin-left: 20px;
input[type="button"]:focus {
outline: none;
input.three-lines {
margin-left: 18px;
background: none;
border: none;
border-bottom: 1px solid #b3c1cc;
width: 150px;
margin-bottom: 30px;

<div id="page2-content">
<div class="input-group" id="previousTeachingExperience">
<label id="teachingExpierience">Teaching Experience *</label>

<div id="employmentHistory">
<input type="text" class="three-lines" name="schoolBoard_1" placeholder="School Board" onblur="this.placeholder='Email'" onfocus="this.placeholder=''" />
<input type="text" class="three-lines" name="position_1" placeholder="Position" onblur="this.placeholder='Position'" onfocus="this.placeholder=''" />
<input type="text" class="three-lines" name="years_1" />
<input type="button" name="myButton" onclick="addJob()" value="+" />

Answer Source

You function is right just add the paramter "this" when you put the function in the onclick attribute, like this: