大家好我编写了一个脚本,只允许在文本框中使用小数
function onlyDecimal(evt) {
if (!(evt.keyCode == 46 || (evt.keyCode >= 48 && evt.keyCode <= 57)))
return false;
var parts = evt.srcElement.value.split('.');
if (parts.length > 2)
return false;
if (evt.keyCode == 46)
return (parts.length == 1);
if (parts[0].length >= 15)
return false;
if (parts[1].length >= 3)
return false;
}
<asp:TextBox ID="txtDecimal" runat="server" OnKeyPress="return onlyDecimal(event)" />
这只允许以下输入
1.000
12.000
123.123
但是我想限制十进制之前的十进制后面的数字,它可以接受最多15位数,所以有些人可以帮助我像下面的1234.123,12345.123
等等
此外,如果我输入12.123
并尝试编辑小数部分,则在我清除该值之前不允许我编辑该值
答案 0 :(得分:1)
您可以在文本框中添加“FilterNumber”类并实现jquery以实现您的功能
<asp:TextBox ID="txtDecimal" CssClass="FilterNumber" runat="server" />
$(".FilterNumber").live("keypress", function (e) {
var caretPosition = doGetCaretPosition(this);
var code = (code ? code : e.which);
//if it is delete,navigation keys always allow
if (code == 0 || code == 8)
return true;
var Value = $(this).val();
if (Value.indexOf('.') != -1) {
var splt = Value.split('.');
var indexofDot = Value.indexOf('.');
if (caretPosition > indexofDot) {
//allow only three character after .
if (splt[1].length > 2) {
return false;
}
}
else {
//allow only fifteen character before .
if (splt[0].length > 14) {
return false;
}
}
}
if (code != 46 && code > 31 && (code < 48 || code > 57))
return false;
//if it is (.)
else if (code == 46) {
var Value = $(this).val();
//if value already contains (.) character
if (Value.indexOf('.') != -1) {
var splt = Value.split('.');
//if there is already(.) char then return false
if (splt.length >= 2)
return false;
}
}
return true;
});
您需要文本框上的插入位置,以便您可以知道之前是否输入了数字。或之后。
function doGetCaretPosition(oField) {
// Initialize
var iCaretPos = 0;
// IE Support
if (document.selection) {
// Set focus on the element
oField.focus();
// To get cursor position, get empty selection range
var oSel = document.selection.createRange();
// Move selection start to 0 position
oSel.moveStart('character', -oField.value.length);
// The caret position is selection length
iCaretPos = oSel.text.length;
}
// Firefox support
else if (oField.selectionStart || oField.selectionStart == '0')
iCaretPos = oField.selectionStart;
// Return results
return (iCaretPos);
}