0

I am trying to create a button on a button click and if this created button is also clicked there should be another action.

Here is my code:

//EDIT FUNCTION
            $('.edit').on('click', function(e){
                e.preventDefault();
                content = $(this).prop('name');
                id = $(this).prop('id');
                if(!document.getElementById('editnews')) {
                    jQuery('#edit').append('</br><textarea id="editnews" value="'+id+'"></textarea></br>');//is not shown, needed to stop, damn online lib
                    jQuery('#edit').append('<button name="'+id+'" class="saveedit btn btn-success btn-mini"><span class="glyphicon glyphicon-pencil"></span> Save</button>');
                }
                $('#editnews').val(content);
            });

        // EDIT (SEND) FUNCTION
        $('.saveedit').on('click', function(e){
            console.log("oke");
            e.preventDefault();
            $.ajax({
                type: 'POST',
                url: 'index.php?page=news',
                data: {editid:$(this).prop('name'), editcontent:$('#editnews').val()}
            }).done(function(response) {
                location.reload();
            });
        });

So the first edit function works fine, but the second not as the button could not be tracked. Hope you can help meh

Cr41s3
  • 97
  • 2
  • 11

2 Answers2

0

You need to use event-delegation in order to bind event for dynamically created element

$('#edit').on('click','.saveedit', function(e){
    console.log("oke");
    e.preventDefault();
    $.ajax({
        type: 'POST',
        url: 'index.php?page=news',
        data: {editid:$(this).prop('name'), editcontent:$('#editnews').val()}
    }).done(function(response) {
        location.reload();
    });
});
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
0

Its not working because the event is attached to the .saveedit that is available in the DOM at the time when the script got executed. Any dynamically created .saveedit won't have this event attached.

What you have to do is attach the click event upon document i.e. handle it whenever any .saveedit is clicked that exists inside document:

 $(document).on('click', '.saveedit', function(e){
            console.log("oke");
            e.preventDefault();
            $.ajax({
                type: 'POST',
                url: 'index.php?page=news',
                data: {editid:$(this).prop('name'), editcontent:$('#editnews').val()}
            }).done(function(response) {
                location.reload();
            });
        });
Kamran Ahmed
  • 11,809
  • 23
  • 69
  • 101