IF condition in jQuery

Asked

Viewed 2,233 times

0

I am trying to add an IF condition to my study exercise in jQuery and I have a small problem.

the code below creates a short list of tasks and when clicked on the div created by jquery it is deleted.`

var main = function(){
  $('#button').click(function(){
    var item = $('input[name=txtTarefa]').val();
    $('.lista').append('<div class="item">' + item + '</div>');
    })
    $(document).on('click', '.item', function(){
    $(this).remove();
      })
  }
$(document).ready(main)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>

<div class="painel">
  <label for="acao">Tarefa:</label>
  <input type="text" name="txtTarefa" class="tarefa" />
  <button name="btn" id="button">Adicionar</button>
</div>

<br />

<div class="lista">
  
</div>

The problem is that if I try to create a condition before deleting the item the condition is not executed. for example;

$(document).on('click', '.item', function(){
var apagar = confirm("Deseja apagar a tarefa?");
if (apagar){
$(this).remove(); }
  })
  • I didn’t really understand what the problem is and how to reproduce it.

  • I tried to add an IF to ask the user if he wants to delete a DIV and that IF doesn’t work.

  • 2

    I tested it here and it worked normally, see if that’s what you want: http://jsfiddle.net/mzrhefh0/

  • Almeida, it did work. in codepen.io is not working.

1 answer

1

Notice you’re using the version 1.2.3 jQuery. This version is very old and does not yet have the method .on() entered in the verse 1.7. Switch to a more current version and it will work.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<div class="painel">
    <label for="acao">Tarefa:</label>
    <input type="text" name="txtTarefa" class="tarefa" />
    <button name="btn" id="button">Adicionar</button>
</div>
<br />
<div class="lista"></div>

jsFiddle: https://jsfiddle.net/j49m5khg/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.