0

I have this and it's working:

function cancelFunction(targetid,e) {
    if (targetid.substring(0,9) == "editinput") {
        if (e.keyCode != 27) {
            return;
        }
        var target = targetid.substring(10);
    }
    else
        var target = targetid.substring(11);
    // DO OTHER STUFF HERE
}
$(\'[id^=editinput]\').keypress(function(e) {
    var targetid= $(this).attr("id");
    cancelFunction(targetid,e);
});
$(\'[id^=canceledit]\').click(function() {
    var targetid= $(this).attr("id");
    cancelFunction(targetid,"");
});

What i want to know if it's this possible to merge keypress event on [id^=editinput] and click event on [id^=canceledit] in a single call with function declared after that?

I mean something like this (obviously wrong syntax):

$((\'[id^=canceledit]\').click)((\'[id^=editinput]\').keypress)(function(e) {
    var targetid = $(this).attr("id");
    if (targetid.substring(0,9) == "editinput") {
        if (e.keyCode != 27) {
            return;
        }
        var target = targetid.substring(10);
    }
    else
        var target = targetid.substring(11);
    // DO OTHER STUFF HERE
});

1 Answer 1

2

The easiest would probably be to refactor a little

function cancelFunction(e) {
    if (this.id.substring(0,9) == "editinput") {
        if (e.keyCode != 27) {
            return;
        }
        var target = this.id.substring(10);
    } else {
        var target = this.id.substring(11);
    }
}

$('[id^=editinput]').on('keypress', cancelFunction);
$('[id^=canceledit]').on('click', cancelFunction);
Sign up to request clarification or add additional context in comments.

3 Comments

Ok, this is better than nothing, but does it mean what i'm trying to do (merge all 3 parts) is impossible? (PS: you forgot to move var targetid = $(this).attr("id"); as first line of cancelFunction)
I didn't move that line as it's not needed, I'm using this.id instead. It's not impossible to merge all three parts, but it will be more complicated and with more code than doing it this way.
Ok yeah, sorry, didnt notice you changed targetid to this.id

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.