输入字段中有一些逗号分隔值。当我按下COMMA(,
)或ENTER键时,我想提醒一条消息。我已经给出了我用于此的代码,但是没有用。这有什么低效的吗?
$(document).on("keyup", '.tagsinput', function (e) {
if (e.which == 13 || e.which == 44) {
alert('comma added');
}
});
答案 0 :(得分:11)
逗号的keycode
(jQuery中为which
)为188
这个here
有一个很棒的工具答案 1 :(得分:4)
_blank
答案 2 :(得分:2)
尝试使用UIImage
代替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
}
});
});
答案 3 :(得分:0)
你不应该听取密钥,更好的方法是听取按键:
$('.tagsinput').keypress(function (e) {
if (e.which == 13 || e.which == 44) {
alert('comma added');
}
});
Jsfiddle:http://jsfiddle.net/doe7qk6r/
答案 4 :(得分:0)
$(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);
}
}
});
});
&#13;
<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="" />
&#13;
希望这对您有用:)
答案 5 :(得分:0)
event.key
和现代JS!没有数字代码了。您可以直接检查 Enter 或,键。
const input = document.getElementById("inputId");
input.addEventListener("keypress", function (event) {
if (event.key === "Enter" || event.key === ",") {
// Do something
}
});