[英]mask for comma separated numbers list
我正在嘗試為輸入的逗號分隔值創建一個掩碼,但是有很多困難。
你們能幫我嗎?
這是我當前的面具:
<script>
$(document).on("keyup keydown keypress", "commaseparated", function (e) {
if (!$(this).val().match(/^([0-9]{0,1})(,[0-9]{1,}){1,}?$/g)) {
e.preventDefault();
}
});
</script>
<input type="text" class="commaseparated" />
<!-- example input would be
1235 <- single number
or
2654,524874,5456 <- many numbers
-->
提前致謝 :)
編輯嗯,這不完全是一個面具。 我想要的是用戶只能插入數字和逗號,例如:
123 -> allowed
123,123 -> allowed
123,, -> not allowed
123,letters -> not allowed
您可以使用RegExp
/(,|\\D)(?=\\1)|^[,\\D]|[^,\\d]$/g
匹配逗號或非數字字符,后跟逗號或非數字字符字符串開頭的逗號或非數字或字符串的最后一個字符不是數字或逗號,請用空字符串替換匹配項。
$(".commaseparated").on("input", function(e) { $(e.target).prop("value", function(_, val) { return val.replace(/(,|\\D)(?=\\1)|^[,\\D]|[^,\\d]$/g, ""); }) });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <input type="text" class="commaseparated"/>
請嘗試以下jquery。
//We need to capture the keypress event, as this is triggered before the value is displayed in the text box.
$(document).on("keypress", ".commaseparated", function (e) {
var currentValue = $(this).val();
//If the value is empty, let user enter numerals.
if(currentValue == "" && e.keyCode >= 48 && e.keyCode <= 57) {
return true;
}
else {
//If some value is there, get the last character.
var lastChar = currentValue.substr(currentValue.length - 1);
//If the last character is comma, let user enter numerals.
if(lastChar == "," && e.keyCode >= 48 && e.keyCode <= 57){
return true;
}
//If the last character is comma, deny entering comma again.
else if(lastChar == "," && e.keyCode == 44){
return false;
}
//If the control reaches here and as last character could only be numeral, let user enter only comma or numerals.
else if (e.keyCode == 44 || (e.keyCode >= 48 && e.keyCode <= 57)) {
return true;
}
// for everything else, return false.
else{
return false;
}
}
});
在這里找到jsfiddle。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.