Callombert
Callombert

Reputation: 1099

Binding two events to same function

Me again with another issue.

Function does this:

  1. Click edit_qty_button to edit quantity which transforms the current number in an input
  2. Press enter or .done_editing_button once finished.

My issue is that I'm not sure how to attach both the keypress 13 and the click event in order not to have to write the same function twice, any help please?

$(document).on("click", '.edit_qty_button', function() {

    var qty = $(this).parent();
    qty.html('<input class="qty_input_box" type="text" /><br><span class="done_editing_button">Done</span>');

    $('.done_editing_button').on('click', function() {

        var new_qty = $('.qty_input_box').val();
        qty.html(new_qty + '<br><span class="edit_qty_button">Edit</span>');

    });

    $('.qty_input_box').keypress(function(e) {
        if (e.which == 13) {

            var new_qty = $('.qty_input_box').val();
            qty.html(new_qty + '<br><span class="edit_qty_button">Edit</span>');

        }
    });

});

Upvotes: 0

Views: 210

Answers (2)

Jon Spencer
Jon Spencer

Reputation: 39

The syntax might be wrong, but essentially you call the same function from two different events:

$('qty_input_box').onkeypress=checkKeyFunc;  // Capture keypress & go off to check for ENTER

// Capture the button click event
$('done_editing_button').on("click", '.edit_qty_button', function() {TransformsCurrentNumberFunction};

// Function to check if keypress was ENTER
function checkKeyFunc()
{
    if (window.event.keyCode == 13)
    {
        TransformsCurrentNumberFunction;
    }
}

// Function to implement shared logic to run on CLICK or ENTER events
function TransformsCurrentNumberFunc() {
  // Implement your shared logic in this function
}

BTW...you may need to handle the key press differently in IE as compared to Firefox or Chrome. http://forums.codeguru.com/showthread.php?370260-Detect-keypress-of-ENTER

Upvotes: 1

Danny
Danny

Reputation: 7518

Try this

function myFunction() {
    var new_qty = $('.qty_input_box').val();
    qty.html(new_qty + '<br><span class="edit_qty_button">Edit</span>');
}
$('.done_editing_button').on('click', myFunction);
$('.qty_input_box').keypress(function(e) {
    if (e.which == 13) {
        myFunction();
    }
});

Upvotes: 1

Related Questions