aborted
aborted

Reputation: 4541

jQuery click event listener inside keyup event listener

I have a keyup event listener that dynamically creates and adds a new button to the page. Then that button needs another click event listener that depends on data only available inside the keyup listener to do its job.

This is the code I have:

$('.select2-input').on('keyup', function(e) {
    var self = $(this);
    if (self.prev().text() != 'Uhr') {
        return;
    }

    if ($('.select2-no-results').is(':visible')) {
        if (!$('#insertWatch').length) {
            $($('<a href="javascript:;" id="insertWatch" class="btn btn-xs red" style="margin: 10px 0 0 10px;">Uhr Einfügen</a>')).insertAfter(this);
        }
    } else {
        $('#insertWatch').remove();
    }

    $(document).on('click', '#insertWatch', function(e) {
        alert('Added')
        $.post('/insert/watch', { name: self.val() }, function(response) {
            $('#supplier_id').prepend($('<option value="' + response + '" selected>' + self.val() + '</option>'));
            $('.select2-drop-mask, .select2-drop-active').css('display', 'none');
        });

        return false;
    });

    e.stopPropagation();
});

The click event listener does not fire at all when the added button is clicked. I'm unable to figure out why. So to sum this up, alert('Added') never pops up.

Upvotes: 0

Views: 468

Answers (2)

Leo Javier
Leo Javier

Reputation: 1403

Is this what you are looking for? http://jsfiddle.net/leojavier/cp34ybca/

$('.select2-input').on('keyup', function(e) {
    var button = "<button class='myButton'>my button</button>";

    if ($(this).val() != 'Uhr' && !$('.myButton').length) {
       $('body').append(button);
           $('.myButton').on('click', function(){
           $('i').html('Clicked!');
       });
    }else  if ($(this).val() === 'Uhr'){
        $('.myButton').remove();
        $('i').html('');
    }
});

Upvotes: 0

Mark
Mark

Reputation: 4873

Try attaching the even when the element is created.

Something like:

$('.select2-input').on('keyup', function(e) {
    var self = $(this);
    if (self.prev().text() != 'Uhr') {
        return;
    }

    if ($('.select2-no-results').is(':visible')) {
        if (!$('#insertWatch').length) {
            $($('<a href="javascript:;" id="insertWatch" class="btn btn-xs red" style="margin: 10px 0 0 10px;">Uhr Einfügen</a>')).insertAfter(this).on('click', '#insertWatch', function(e) {
        alert('Added')
        $.post('/insert/watch', { name: self.val() }, function(response) {
            $('#supplier_id').prepend($('<option value="' + response + '" selected>' + self.val() + '</option>'));
            $('.select2-drop-mask, .select2-drop-active').css('display', 'none');
        });

        return false;
    });;
        }
    } else {
        $('#insertWatch').remove();
    }



    e.stopPropagation();
});

Upvotes: 1

Related Questions