2013-10-19 45 views
6

我如何格式化數字,因爲我在html輸入框中鍵入它?如何格式化輸入框文本,因爲我打字它

例如,我想鍵入數字2000,當我輸入第4位數字時,文本(當前顯示在文本框中)將自動格式化爲2,000(用逗號)。

//my modified code based on Moob answer below 

<input type="text" class="formattedNumberField" onkeyup="myFunc()"> 

//jQuery 
$(".formattedNumberField").on('keyup', function(){ 
    var n = parseInt($(this).val().replace(/\D/g,''),10); 
    $(this).val(n.toLocaleString()); 
}); 

function myFunc(){ 
// doing something else 
} 

而此代碼的工作完美如圖Moob小提琴,它不是在我結束工作,也許是因爲我有輸入框裏面另一個onkeyup事件???

+1

測試的onkeyup如果字段值就是一些相應 – Moob

+0

@Moob格式化它,你可以告訴我一個例子嗎?謝謝 – annamull654

+0

當然。請參閱下面的答案。 :) – Moob

回答

11

純JS(SANS jQuery的):

var fnf = document.getElementById("formattedNumberField"); 
fnf.addEventListener('keyup', function(evt){ 
    var n = parseInt(this.value.replace(/\D/g,''),10); 
    fnf.value = n.toLocaleString(); 
}, false); 

Native JS Example Fiddle

使用jQuery:

$("#formattedNumberField").on('keyup', function(){ 
    var n = parseInt($(this).val().replace(/\D/g,''),10); 
    $(this).val(n.toLocaleString()); 
    //do something else as per updated question 
    myFunc(); //call another function too 
}); 

With jQuery Example Fiddle

允許小數:

$("#formattedNumberField").on('keyup', function(evt){ 
    if (evt.which != 110){//not a fullstop 
     var n = parseFloat($(this).val().replace(/\,/g,''),10); 
     $(this).val(n.toLocaleString()); 
    } 
}); 

Obligatory Example

+0

這是更好! ;) – annamull654

+0

雖然小提琴的工作完美,它不能在我的最後工作,因爲我已經有一個onkeyup,在輸入框中激起一個功能。我怎樣才能繞過這個?任何想法?謝謝 – annamull654

+0

你使用jQuery或原生JS?最可能的解決方案是將這兩個功能合併爲一個。更新你的問題,包括你的關鍵功能(或發佈小提琴) – Moob

2

試試這個插件,它的工作原理相當不錯http://robinherbots.github.io/jquery.inputmask/

+0

這是非常接近我想要的。將嘗試它,如果它適用於我..我會讓你知道。謝謝 – annamull654

+0

雖然這看起來很有前途..我儘量減少插件的使用,並且@Moob展示了一個完美的例子。無論如何感謝:) – annamull654

0

根據您所給出的例子,你可以使用這樣的事情:

$("#my_textbox").keyup(function(){ 
    if($("#my_textbox").val().length == 4){ 
     var my_val = $("#my_textbox").val(); 
     $("#my_textbox").val(Number(my_val).toLocaleString('en')); 
    } 
}); 

我用jQuery的在上面,但它可以是也用純JS完成。

工作實施例here

+0

NaN如果用戶輸入的東西不是數字! – Moob

+0

@Moob你必須添加更多的JavaScript來驗證不同的場景 –

6

與其他答案的一些代碼位,我創建了以下工作的例子。代碼沒有jQuery,但比其他一些例子長一點。但它需要關注其他人的許多問題。

http://jsfiddle.net/kcz4a2ca/10/

代碼:

var input = document.getElementById('my_textbox'); 
var currentValue; 

input.addEventListener('input', function(event) { 
    var cursorPosition = getCaretPosition(input); 
    var valueBefore = input.value; 
    var lengthBefore = input.value.length; 
    var specialCharsBefore = getSpecialCharsOnSides(input.value); 
    var number = removeThousandSeparators(input.value); 

    if (input.value == '') { 
    return; 
    } 

    input.value = formatNumber(number.replace(getCommaSeparator(), '.')); 

    // if deleting the comma, delete it correctly 
    if (currentValue == input.value && currentValue == valueBefore.substr(0, cursorPosition) + getThousandSeparator() + valueBefore.substr(cursorPosition)) { 
    input.value = formatNumber(removeThousandSeparators(valueBefore.substr(0, cursorPosition-1) + valueBefore.substr(cursorPosition))); 
    cursorPosition--; 
    } 

    // if entering comma for separation, leave it in there (as well support .000) 
    var commaSeparator = getCommaSeparator(); 
    if (valueBefore.endsWith(commaSeparator) || valueBefore.endsWith(commaSeparator+'0') || valueBefore.endsWith(commaSeparator+'00') || valueBefore.endsWith(commaSeparator+'000')) { 
    input.value = input.value + valueBefore.substring(valueBefore.indexOf(commaSeparator)); 
    } 

    // move cursor correctly if thousand separator got added or removed 
    var specialCharsAfter = getSpecialCharsOnSides(input.value); 
    if (specialCharsBefore[0] < specialCharsAfter[0]) { 
     cursorPosition += specialCharsAfter[0] - specialCharsBefore[0]; 
    } else if (specialCharsBefore[0] > specialCharsAfter[0]) { 
     cursorPosition -= specialCharsBefore[0] - specialCharsAfter[0]; 
    } 
    setCaretPosition(input, cursorPosition); 

    currentValue = input.value; 
}); 

function getSpecialCharsOnSides(x, cursorPosition) { 
    var specialCharsLeft = x.substring(0, cursorPosition).replace(/[0-9]/g, '').length; 
    var specialCharsRight = x.substring(cursorPosition).replace(/[0-9]/g, '').length; 
    return [specialCharsLeft, specialCharsRight] 
} 

function formatNumber(x) { 
    return getNumberFormat().format(x); 
} 

function removeThousandSeparators(x) { 
    return x.toString().replace(new RegExp(escapeRegExp(getThousandSeparator()), 'g'), ""); 
} 

function getThousandSeparator() { 
    return getNumberFormat().format('1000').replace(/[0-9]/g, '')[0]; 
} 

function getCommaSeparator() { 
    return getNumberFormat().format('0.01').replace(/[0-9]/g, '')[0]; 
} 

function getNumberFormat() { 
    return new Intl.NumberFormat(); 
} 

/* From: http://stackoverflow.com/a/6969486/496992 */ 
function escapeRegExp(str) { 
    return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); 
} 

/* 
** Returns the caret (cursor) position of the specified text field. 
** Return value range is 0-oField.value.length. 
** From: http://stackoverflow.com/a/2897229/496992 
*/ 
function getCaretPosition (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; 
} 

/* From: http://stackoverflow.com/a/512542/496992 */ 
function setCaretPosition(elem, caretPos) { 
    if(elem != null) { 
     if(elem.createTextRange) { 
      var range = elem.createTextRange(); 
      range.move('character', caretPos); 
      range.select(); 
     } 
     else { 
      if(elem.selectionStart) { 
       elem.focus(); 
       elem.setSelectionRange(caretPos, caretPos); 
      } 
      else 
       elem.focus(); 
     } 
    } 
} 
+1

這是最好的答案,doesn不會遇到空場問題,並且可以在不丟失光標位置的情況下編輯中間的數字,但確實遭受不是v的字符alid編號導致錯誤而不是被忽略。 – Graham

+0

我該怎麼做,只能用逗號代替點作爲分隔符? – Tinmar

+0

我明白了 - 它需要'en'的論點。 'Intl.NumberFormat('en');' 此外,這顯然是最好的答案 - 它解決了光標位置問題! – Tinmar