2013-10-19 8 views
6

Jak sformatować numer podczas wpisywania go w polu wprowadzania html?Jak sformatować tekst pola wprowadzania, gdy go piszę?

więc na przykład, chcę wpisać liczbę 2000, w chwili wpisania czwartej cyfry, tekst (obecnie wyświetlany w polu tekstowym) zostanie automatycznie sformatowany na 2000 (z przecinkiem).

//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 
} 

gdy ten kod działa idealnie jak pokazano na Moob Fiddle, jej nie działa na moim końcu może dlatego, że mam inny onkeyup zdarzenia wewnątrz inputbox ???

+1

onkeyup testu, jeśli wartość pola jest liczbą następnie sformatować go odpowiednio – Moob

+0

@Moob można pokazać mi przykład proszę? dzięki – annamull654

+0

Oczywiście. Zobacz moją odpowiedź poniżej. :) – Moob

Odpowiedz

11

Czyste JS (jQuery) Sans:

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

z 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

Aby umożliwić dziesiętne:

$("#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

to jest lepsze! ;) – annamull654

+0

choć Fiddle działa idealnie, nie działa na moim końcu, ponieważ mam już onkeyup, który uruchamia funkcję w polu wejściowym. jak mogę to obejść? dowolny pomysł? dzięki – annamull654

+0

Używasz jQuery lub natywnego JS? Najbardziej prawdopodobnym rozwiązaniem jest połączenie dwóch funkcji w jedną.Zaktualizuj swoje pytanie, aby dołączyć funkcję keyup (lub opublikuj skrzypce). – Moob

0

oparciu o przykład dałeś, można użyć coś takiego:

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

użyłem jQuery powyżej, ale może być również z czystym JS.

przykład roboczych here

+0

NaN, jeśli użytkownik wpisze coś, co nie jest numerem! – Moob

+0

@Moob Musisz dodać więcej skryptów JavaScript do sprawdzania poprawności dla różnych scenariuszy. –

6

Z niektórych bitów kodu innych odpowiedzi stworzyłem następujący przykład pracy. Kod jest bez jquery, ale nieco dłuższy niż inne przykłady. Ale zajmuje się wieloma problemami, które mają inni.

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

Kod:

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

To jest najlepsza odpowiedź, doesn nie ma problemu z pustym polem i może edytować liczbę w środku bez utraty pozycji kursora, ale cierpi na znaki, które nie są v numer alid powodujący błąd zamiast po prostu ignorowany. – Graham

+0

Jak to zrobić, tylko z przecinkami zamiast kropek jako separatory? – Tinmar

+0

Mam to - potrzebowałem argumentu "en". 'Intl.NumberFormat ('pl');' Jest to oczywiście najlepsza odpowiedź - problem z pozycją kursora rozwiązany! – Tinmar

Powiązane problemy