Krzysztof Delestowicz
Krzysztof Delestowicz

Reputation: 129

Add a special character on keypress not working

I would like to add an accented character – á – whenever we use a key combination of Alt + 'a'. Then the same for é with the combination of Alt + 'e'.

I tried to achieve it with this function, however, the results are far from perfect:

$('input').bind('keypress keydown keyup', function(event) {
    if (event.altKey && event.key == 'a') {
        event.preventDefault();
        this.value += 'á';
    }
});

When I use this key combination, I don't get the desired result, instead, I get the Polish "ą".

However, when I only use event.key == 'a' without the event.aktKey, it works and adds value to the input.

Could you please explain why this happens and provide a solution? Thank you.

Upvotes: 0

Views: 791

Answers (1)

MikeM
MikeM

Reputation: 13641

There is no reason within your code or jquery that you would get "ą".

But anyway, why bind to all three events: keypress, keydown and keyup? That will result in multiple characters being added for a single key press.

The following seems to work fine.

$('input').on('keydown', function (event) {
    if (event.altKey && event.key == 'a') {
        event.preventDefault();
        this.value += 'á';
    }
});

console.log('\xE1' === 'á');    // true
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input></input>

Upvotes: 1

Related Questions