[英]How do I prevent my smooth-scroll jquery function from modifying the contents of my div elements?
[英]How do I prevent my decimals to be erased in Jquery?
所以我正在處理一個表單,並且有一個字段,在小數點分隔符后應允許5個小數。 但是,我還必須在.focus()和上進行這項工作。 blur()事件,它可以正常工作。 但是,當我單擊else時,要在輸入字段中設置所需的值格式,從我的5個小數中刪除了我的最后2個。 例如:我輸入78676,56569,重新返回78.676,565如何更改代碼以不刪除最后2個小數? 這是我所擁有的:
function fiveDecimals(event) {
var $txtBox = $(this);
var key = window.event ? event.keyCode : event.which;
if (event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 37 || event.keyCode == 39) {
return true;
} else if ( key < 44 || key > 57 && event.keyCode != 44) {
event.preventDefault();
}else {
var len = $txtBox.val().length;
var index = $txtBox.val().indexOf(',');
if (index > 0 && event.keyCode == 44) {
return false;
} //prevent if already comma
if (index > 0) {
var charAfterdot = (len + 1) - index;
//allows only 5 decimals
if (charAfterdot > 6) {
return false;
}
}
}
return $txtBox;
};
var
dec_separator = (0.1).toLocaleString().substr(1,1), // Get decimal separator
dec_xsanitize = new RegExp('[' + dec_separator + ']', 'g'), // Get thousands separator
tho_separator = (1000).toLocaleString().substr(1,1),
tho_xcleaner = new RegExp('[' + tho_separator + ']', 'g');
$('#float2')
.on("focus", function ()
{
this.value = this.value.replace( tho_xcleaner, '' );
})
.on("blur", function ()
{// Clean thousands separator and change decimal separator
var number = parseFloat(this.value.replace( tho_xcleaner, '' ).replace( dec_xsanitize, '.' ));
this.value = isNaN(number) ? '0': number.toLocaleString();
});
這是Jsfiddle: http : //jsfiddle.net/Daria90/zuxu5tva/
請注意,我的小數點分隔符是在DE系統上設置的,因此在英文鍵盤上可能是一個句點,keyCode是46。我的是44。
您需要包括的只是$(this).val(number);
在您的blur
功能中
$('#float2')
.on("focus", function ()
{
this.value = this.value.replace( tho_xcleaner, '' );
})
.on("blur", function ()
{// Clean thousands separator and change decimal separator
var number = parseFloat(this.value.replace( tho_xcleaner, '' ).replace( dec_xsanitize, '.' ));
this.value = isNaN(number) ? '0': number.toLocaleString();
$(this).val(number);
});
查看小提琴鏈接
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.