1

I have created two scripts for managing a list. One for adding a li element in the page and saving it to the database, and the other one, for removing it. The fact is, when I create a li element, the second script (remove one), doesn't take effect on it (I must update the page to remove it). How can I make it work?

I leave you both scripts:

Adding:

function afegir() {

    var fnom=document.getElementById('compranom').value;
    var fnum=document.getElementById('quantitat').value;
        $.ajax({
            data: {
                "nom": fnom,
                "num":fnum
            },
            url:   'afegir.php',
            type:  'post',
            beforeSend: function () {
            },
            success:  function (response) {
            if(response!="-1") {
                $('.llista').append('<li value="'+fnum+'" id="'+response+'" >'+fnom+'</li>');
            }
            else{
            alert('Error');
            }
            }
        }); 
    }

Removing:

$(document).ready(function(){
$(".list li").click(function() {
var fid=$(this).attr('id');
    $.ajax({
        data: {
            "id": fid
        },
        url:   'treure.php',
        type:  'post',
        beforeSend: function () {
        },
        success:  function (response) {
        if(response=="si") {
            $("#"+fid+"").remove();
        }
        else{
        alert('Error');
        }
        }
    }); 
});

});

Thank you for your help.

2 Answers2

2

use on event delegation for this..

$(document).ready(function(){
 $(".list").on('click','li',function() {
    var fid=$(this).attr('id');
    $.ajax({
      data: {
        "id": fid
      },
      url:   'treure.php',
      type:  'post',
      beforeSend: function () {
      },
      success:  function (response) {
        if(response=="si") {
          $("#"+fid+"").remove();
        }
        else{
           alert('Error');
        }
       }
   }); 

 });
});

link here to read more about on delegated event

bipen
  • 36,319
  • 9
  • 49
  • 62
  • Without $(document).ready(function(){ ? –  Feb 20 '13 at 13:55
  • inside `$(document).ready(function(){ ` – bipen Feb 20 '13 at 13:57
  • Now shows me this error (PHP): `
    Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in /home/s120321b/public_html/afegir.php on line 9
    `
    –  Feb 20 '13 at 13:58
  • that is your PHP error in afegir.php... check the query you are doing is correct... – bipen Feb 20 '13 at 14:00
  • 1
    @albert: Thats on the PHP side and has nothing to do with the js unless you are sending the parameters your php expects incorrectly. – prodigitalson Feb 20 '13 at 14:02
0

Can use live() for getting to newly created elements: http://api.jquery.com/live/

Description: Attach an event handler for all elements which match the current selector, now and in the future.

JBar
  • 373
  • 2
  • 6