0

I am trying to dynamically add and remove divs from a page. The divs have inner divs. I have the add functionality working and I can get the first div created to delete. My problem is that I have modified the remove div functionality and I believe it is just a syntax problem that is stopping this from working. Any pointers?

This code adds the divs I want and is working:

<!--This appends all elements necessary to complete a new step. The divs are nested within the answer_step div here -->
    $("button.add_answer_step_button").click(function () {
        $new_step = $("div.answer_steps").append($('<div id = answer_step_' + answer_identifier_number + ' class = "answer_step">').append($('<div class="answer_step_equation" contenteditable="true" placeholder="Enter The Next Solution Step This Question">')).append($('<div class = "answer_step_description" contenteditable="true" placeholder="Enter A Description as to how this step was reached or how to solve the next step">')).append($('<button class = "remove_answer_step_button">- Remove This Step</button>')));

        <!--Increase identifier number by 1-->
        answer_identifier_number++;
    });

This next code is meant to remove any div for which the remove step button is pressed. I can getting it working for the first one with a bit of code change but I believe that the code below should work for them all. I'm stuck here:

$("#remove_answer_step_button").click(function () {
        $(this).parent().remove();
    });

I have a fiddle created for this here https://jsfiddle.net/max_m/5r07utj1/

The functionality to add a new div with inner divs works locally for me but not in the fiddle.

Anyway, to my main question - I can get the remove div to work for the first div that is added but not subsequent divs that are added to the page. I think it is only a syntax problem as I have taken this code from someone else here.

A solution was found:

    $(document).on('click','.remove_answer_step_button', function () {
        $(this).parent().remove();
    });
Rachel Gallen
  • 27,943
  • 21
  • 72
  • 81
KPM
  • 181
  • 4
  • 23
  • 1
    An element's `id` should be a *unique* string (it should only appear once in the DOM). Also, this `'
    '` is not valid. Overlooking the non-unique id, it should be: `'
    '` (needs end quote).
    – noahnu May 18 '16 at 23:04
  • 1
    Any time you are referencing something that has more than one instance on the page you should be referencing it by the class name (not by ID as mentioned in the comment above). – Jonathan Gray May 18 '16 at 23:09
  • What version of jQuery are you using? `.live()` was removed in 1.9, and replaced with `.on()` which has similar but differing syntax. – jmoerdyk May 18 '16 at 23:12
  • Thanks noahnu, jmoerdyk, Jonathan Gray. Copy/paste error on my part there for the missing " - Fixed in Fiddle and above. I'll follow up on your advice and fix up this code. The .live, I found on here and swapped over to it. Wasn't sure what it did but the fiddle I was looking at worked with it so I thought I'd see if it worked for me. – KPM May 18 '16 at 23:15
  • https://jsfiddle.net/5r07utj1/10/ https://learn.jquery.com/events/event-delegation/ – sinisake May 18 '16 at 23:32
  • add function(e) and then do e.target to get the nearest one. You're missing the e (event). – Ronnie Royston May 18 '16 at 23:40

1 Answers1

0

Here's a full working example of what you are trying to accomplish (i think). Its based on your code but it includes ko bindings. There is actually a much shorter way of doing it (html wise) but i didn't want to confuse you too much.

I don't know why the code snippet gives an error, it runs fine on the fiddle.

https://jsfiddle.net/RachGal/na38tmog/

answer_identifier_number = 0;

$(document).on('click', '.add_answer_step_button', function() {
  $new_step = $("#answer_steps").append($('<div id="answer_step' + answer_identifier_number + '" class = "answer_step draggable" data-bind="draggable:true,droppable:true">').append($('<div id="answer_step_equation' + answer_identifier_number + '" class="answer_step_equation" contenteditable="true" placeholder="Enter The Next Solution Step This Question">')).append($('<div id="answer_step_description' + answer_identifier_number + '" class = "answer_step_description" contenteditable="true" placeholder="Enter A Description as to how this step was reached or how to solve the next step">')).append($('<div class="buttons"><button class = "remove_answer_step_button">- Remove This Step</button><button class = "add_answer_step_button">+Add Next Step</button></div>')));

  answer_identifier_number++;
});
var no_children = $('.answer_step_equation').length;

if (no_children == 1) {
  $('.remove_answer_step_button').attr('disabled', true);
  $('.remove_answer_step_button').css("visibility", "hidden");
}

$(document).on('click', '.remove_answer_step_button', function() {
  $(this).parent().parent().remove();
});

var draggableArguments = {
  revert: 'invalid',
  helper: 'clone',
  appendTo: '#answer_steps',
  refreshPositions: true,
  containment: 'parent',
  zIndex: 1500,
  addClasses: false
};

$('#answer_steps').sortable();


var count = 0;
var selectedDraggable;

ko.bindingHandlers.draggable = {
  init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
    $(element).draggable();
    var list = valueAccessor();
    $(element).sortable({
      update: function(event, ui) {
        //retrieve our actual data item
        var answer_step = ko.dataFor(ui.answer_step.get(0));
        //figure out its new position
        var position = ko.utils.arrayIndexOf(ui.answer_step.parent().children(), ui.answer_step[0]);
        //remove the item and add it back in the right spot
        if (position >= 0) {
          list.remove(answer_step);
          list.splice(position, 0, answer_step);
        }
        ui.answer_step.remove();
      }
    });
    $(element).on('click', function() {
      selectedDraggable = $(this);
    });
  }
};

var vm = function() {
  var self = this;
  self.answer_steps = ko.observableArray();
  self.answer_step = ko.observable('');
  self.init = function() {
    self.answer_steps([]);
  };
  self.remove = function(answer_step) {
    self.answer_steps.remove(answer_step);
  };
  self.addNew = function() {
    self.answer_steps.push(self.answer_step());
    self.answer_step('');
  };
  self.init();
};

ko.applyBindings(new vm());
#answer_steps {
  display: block;
  margin-top: 40px;
  width: 100%;
}
.answer_step {
  display: block;
  position: relative;
  width: 98%;
  height: 200px;
}
.draggable {
  border: solid 1px gray;
}
#buttons {
  width: 98%;
  display: block;
}
.answer_step_equation {
  float: left;
  border: 1px solid black;
  background-color: #F0F4F5;
  width: 60%;
  height: 150px;
  margin-top: 20px;
  margin-bottom: 5px;
  text-align: left;
  overflow-x: hidden;
  overflow-y: auto;
}
.answer_step_description {
  float: right;
  border: 1px solid black;
  background-color: #F0F4F5;
  width: 38%;
  height: 150px;
  margin-top: 20px;
  margin-bottom: 5px;
  text-align: justify;
  overflow-x: hidden;
  overflow-y: auto;
}
[contenteditable=true]:empty:not(:focus):before {
  content: attr(placeholder);
  color: #96ADB5;
  text-align: justify;
  font-size: 14pt;
  font-style: italic;
  display: block;
}
button.add_answer_step_button {
  float: right!important;
  width: 200px;
  height: 25px;
  font-size: 12pt;
  font-weight: bold;
  border-radius: 5px;
  background-color: #eee;
  color: #444;
  border: solid 1px gray;
}
button.remove_answer_step_button {
  display: block;
  visibility: visible;
  float: left;
  width: 200px;
  height: 25px;
  font-size: 12pt;
  font-weight: bold;
  border-radius: 5px;
  background-color: #eee;
  color: #444;
  border: solid 1px gray;
}
button.add_answer_step_button:active,
button.add_answer_step_button:hover,
button.remove_answer_step_button:active,
button.remove_answer_step_button:hover {
  background-color: #CDEDF7;
  border: 1px solid blue;
  cursor: pointer;
}
<!doctype html>
<html>
<head>
<link href="https://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div class="center_column" id="center_column">
  <!--Put in the Plus Sign, Equation and text instruction to allow the user to add a new Div to write the solution and directions-->
  <div id="answer_steps" class="answer_steps" data-bind="foreach:answer_steps">

    <!--Div contains each answer step-->
    <div id="answer_step" class="answer_step draggable" data-bind="draggable:true,droppable:true">
      <!--This placeholder text will empty the div once the user starts typing-->
      <div id="answer_step_equation" class="answer_step_equation" contenteditable="true" placeholder="Enter The Next Solution Step This Question"></div>
      <div id="answer_step_description" class="answer_step_description" contenteditable="true" placeholder="Enter A Description as to how this step was reached or how to solve the next step"></div>
      <!-- Buttons to dynamically add and remove answer divs. The remove functionality is added in JQuery for the add button-->
      <div class="buttons">
        <button class="add_answer_step_button">+ Add next Step</button>
        <button class="remove_answer_step_button">- Remove This Step</button>
      </div>
    </div>
  </div>
</div>
  </body>
  </html>
Rachel Gallen
  • 27,943
  • 21
  • 72
  • 81