Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect Comma/Enter key press

There are some comma separated values in an input field. I want to alert a message when I am pressing the COMMA(,) or ENTER key. I have given the code that I used for this, but didn't work. Is there anything inefficient about this?

$(document).on("keyup", '.tagsinput', function (e) {
    if (e.which == 13 || e.which == 44) {
        alert('comma added');
    }
});
like image 861
Neethu Kp Avatar asked Jun 10 '15 10:06

Neethu Kp


3 Answers

Use event.key and modern JS!

No number codes anymore. You can check for Enter or , key directly.

const input = document.getElementById("inputId");
input.addEventListener("keypress", function (event) {
    if (event.key === "Enter" || event.key === ",") {
        // Do something
    }
});

Mozilla Docs

Supported Browsers

like image 197
Gibolt Avatar answered Oct 04 '22 06:10

Gibolt


The keycode (which in jQuery) for a comma is 188

There is a brilliant tool for this here

like image 21
Alex McMillan Avatar answered Oct 04 '22 05:10

Alex McMillan


$(document).on("keyup", '.tagsinput', function (e) {
    if (e.keyCode == 188) { // KeyCode For comma is 188
        alert('comma added');
    }
});

Demo: http://jsfiddle.net/tusharj/3yLwgwhb/

like image 36
Tushar Avatar answered Oct 04 '22 06:10

Tushar