繁体   English   中英

检测逗号/按Enter键

[英]Detect Comma/Enter key press

输入字段中有一些逗号分隔值。 当我按下COMMA( , )或ENTER键时,我想提醒一条消息。 我已经给出了我用于此的代码,但是没有用。 这有什么低效的吗?

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

keycodewhich jQuery中)为逗号是188

有一个辉煌的工具,这在这里

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

演示: http//jsfiddle.net/tusharj/3yLwgwhb/

尝试使用keypress而不是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' /> 

你不应该听keyup,更好的方法是听keypress:

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

Jsfiddle: http//jsfiddle.net/doe7qk6r/

 $(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="" /> 

希望这对你有用:)

使用event.key和现代JS!

没有数字代码了。 您可以直接检查Enter键。

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

Mozilla文档

支持的浏览器

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM