Comma Detection / Enter Key Press

There are some values ​​in the input field, separated by a comma. I want to warn the message when I press the COMMA ( , ) or ENTER key. I gave the code that I used for this, but did not work. Is there anything ineffective in this regard?

 $(document).on("keyup", '.tagsinput', function (e) { if (e.which == 13 || e.which == 44) { alert('comma added'); } }); 
+6
source share
6 answers

keycode ( which in jQuery) for the comma is 188

There is a great tool for here.

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

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

+4
source

Try using keypress instead of keyup :

 $(function() { //<-- you are missing this $(document).on("keypress", '.tagsinput', function(e) { //<-- note, its keypress console.log('key pressed ', e.which); if (e.which == 13 || e.which == 44) { return false; //<-- prevent } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <input type='text' class='tagsinput' /> <input type='text' class='tagsinput' /> 
+2
source

You should not listen to the keyboard, it is best to listen to a key press:

 $('.tagsinput').keypress(function (e) { if (e.which == 13 || e.which == 44) { alert('comma added'); } }); 

Jsfiddle here: http://jsfiddle.net/doe7qk6r/

0
source

 $(document).ready(function(){ $("#tagsinput").bind('keypress', function(e) { var code = e.keyCode || e.which; if(code == 44) { // comma key code is 44 str= $('#tagsinput').val(); str.substring(0, str.length - 2); arr = str.split(","); key = arr[arr.length-1]; arr.splice(arr.length-1, 1); if(arr.indexOf( key )!=-1){ alert("Duplicate detected : "+key); //uncomment the next line to remove the duplicated word just after it detects ! //$('#tagsinput').val(arr); } } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script> <label>Sub Location Names</label> <input name="tagsinput" id="tagsinput" class="tagsinput" data-maxwidth="200" id="ptag" value="" /> 

hope this works for you :)

0
source

Use event.key and modern JS!

No numeric codes. You can directly check the Enter or ,.

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

Mozilla Docs

Supported Browsers

0
source

Source: https://habr.com/ru/post/988843/


All Articles