Thomas Renaud
Thomas Renaud

Reputation: 11

Removing text from a div

I created two buttons. One adds a information from an input and the other one removes the information of the input if it exists within the list.

<div id = inputArea>

<button id= "add">Add</button><input type="text" name="add"></input>

<button id= "remove">Remove</button><input type="text" name="remove"></input>

</div>
<div id= "box"></div>

I mannaged to write the Jquery for add, but not the remove:

$('#add').click(function(){
var toAdd = $('input[name=add]').val();
$('#box').append("<p>" +toAdd+ "</p>");
});

$('#remove').click(function(){
var checkRemove = $('input[name=remove]').val();
(......)
};

Upvotes: 1

Views: 114

Answers (2)

Pranav C Balan
Pranav C Balan

Reputation: 115222

Use filter() method to filter out using custom condition.

$('#remove').click(function(){
  var checkRemove = $('input[name=remove]').val();
  $('#box p').filter(function(){
    return $(this).html() == checkRemove;
  }).remove();
});

$('#add').click(function() {
  var toAdd = $('input[name=add]').val();
  $('#box').append("<p>" + toAdd + "</p>");
});

$('#remove').click(function() {
  var checkRemove = $('input[name=remove]').val();
  $('#box p').filter(function() {
    return $(this).html() == checkRemove;
  }).remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id=inputArea>

  <button id="add">Add</button>
  <input type="text" name="add">

  <button id="remove">Remove</button>
  <input type="text" name="remove">

</div>
<div id="box"></div>

Upvotes: 1

reza
reza

Reputation: 1507

you can use replace function to remove the selected word

$('#add').click(function(){
var toAdd = $('input[name=add]').val();
$('#box').append("<p>" +toAdd+ "</p>");
});

$('#remove').click(function(){
var checkRemove = $('input[name=remove]').val();
var html =$('#box').html();

var res = html.replace("<p>" +checkRemove+ "</p>","");
$('#box').html(res);
});

Upvotes: 0

Related Questions