Search code examples
jqueryparent

After removing parent elements cant get again them


Guys i have a button and texarea and when i click it , an 'input button' and 'text i wrote' show up. After that when i click 'input button' to remove parent elements(that text and input) it works.Everything is normal now. But when i click button again to get 'input button' and 'text i wrote' showed up again, it is not working. Jsfiddle

$(function(){

$('#add').click(function(){
  var myWritting = $('#textarea').val();
    $('#textarea').val('');
  $('#content').html( myWritting +'<input type="submit" value="delete" id="hide"/>')
});

  $('body').on('click', '#hide', function() {
    $(this).parent().remove();
    return false;
});

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="add">Add</button>
<textarea  id="textarea"></textarea>
<div id="content"></div>


Solution

  • You're removing the element that contains your text and input and not just the text and input itself.
    The parent element is needed to be populated by the text and input.


    So you want to have multiple sets of buttons and text that can be removed by their respective buttons, then wrap them in an element so they can be grouped and removed easily.

    $(function(){
    
    $('#add').click(function(){
      var myWritting = $('#textarea').val();
        $('#textarea').val('');
      $('#content').append( '<p>' + myWritting +'<input type="submit" value="delete" class="hide"/></p>')
    });
    
      $('body').on('click', '.hide', function() {
        $(this).parent().remove();
        return false;
    });
    
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <button id="add">Add</button>
    <textarea  id="textarea"></textarea>
    <div id="content"></div>