在price jquery中自动格式化小数位

qhhrdooz  于 2023-11-17  发布在  jQuery
关注(0)|答案(4)|浏览(99)

我试图隐藏小数位on类型input字段一样
数字从0.00开始
因此,在输入字段中,它首先将是0.00
than i类型1比它应该成为0.01
than i type 2 than it should become 0.12
而不是0,所以它应该变成1.20,最后
当我输入0时,它应该变成12.00
0.010.121.2012.00
我尝试了一些在SO中已经给出的方法,但没有成功。
如果可能的话,请给我推荐其他的方法。谢谢。
我试过这样

$(document).on('keyup','.price',function(e){
		var value = $(this).val();
		if(value.length <= 6) {
			if(e.which == 190 || e.which == 46 || e.which == 44 || e.which == 188){
				var amountDots = 0;
				var amountCommas = 0;
				if(value.indexOf(',') > -1){
					amountCommas = value.match(/,/gi).length;
				}
				if(value.indexOf('.') > -1){
					amountDots = value.match(/./gi).length;
				}
				if((amountDots >= 1 && amountCommas >= 1) || amountCommas > 1 || value.length == 1){
					$(this).val(value.substr(0,value.length - 1));
					return false;
				}
				else{
				 	$(this).val(value.substr(0, value.length - 1) + ',');
				}
			}
      
			$(this).val(value/100); //here is the value will insert
      
		} else {
			$(this).val(value.substr(0,value.length - 1))
			return false;
		}
	});

个字符

mpbci0fu

mpbci0fu1#

好吧,完全不同的解决方案,工作时删除字符:

$(document).on('keypress','.price',function(e){
    var char = String.fromCharCode(e.which);
    if(isNaN(char)) char = '';
    var value = $(this).val() + char;
    value = value.replace('.','');
    $(this).val((value/100).toFixed(2));
    if(!isNaN(char)) return false;
}).on('keyup','.price',function(e){
    var value = $(this).val();
    value = value.replace('.','');
    $(this).val((value/100).toFixed(2));
});

字符串
https://jsfiddle.net/14shzdo5/

vngu2lb8

vngu2lb82#

对于每个新的数组,假设它是一个数字,将其附加到末尾,乘以10并显示结果。

p1iqtdky

p1iqtdky3#

以下逻辑适用于基本场景。您可能需要单独处理清除文本输入。

$(document).ready(function() {
  $("#my-input").on('keyup', function(e) {
    
    var v = String.fromCharCode(e.keyCode);

    if (!isNaN(v)) {
      var dv = $("#my-display").val();
      $("#my-display").val(dv + '' + v);
      $(this).val(($("#my-display").val() / 100).toFixed(2));
    }
  });
});

个字符

bogh5gae

bogh5gae4#

派对迟到了,但我想这对以后的人可能会有帮助。涵盖了很多有用的案例。
请在此处试用:https://codepen.io/mswarts/pen/poGbmML

超文本标记语言

<input type="text" class="fixedDecimals" value="0" inputmode="numeric" pattern="[0-9]*" />

字符串

JavaScript脚本

// Configuration variables
let decimalPlaces;
let unit;
let unitPosition; // "before" or "after"
let useDigitSeparator;
let numberSystem;

// Define the number systems
const numberSystems = {
    1: { digitSeparator: ",", decimalSeparator: ".", digitGroups: 3 },
    2: { digitSeparator: ".", decimalSeparator: ",", digitGroups: 3 },
    3: { digitSeparator: " ", decimalSeparator: ",", digitGroups: 3 },
    4: { digitSeparator: "'", decimalSeparator: ".", digitGroups: 3 },
    5: { digitSeparator: ",", decimalSeparator: ".", digitGroups: 4 },
};

function formatNumber(numStr) {
    const ns = numberSystems[numberSystem];
    let whole, decimal;

    if (decimalPlaces > 0) {
        decimal = numStr.slice(-decimalPlaces).padStart(decimalPlaces, '0');
        whole = numStr.slice(0, -decimalPlaces) || '0';
    } else {
        whole = numStr;
        decimal = '';  // Explicitly set 'decimal' to an empty string when there are no decimal places.
    }

    whole = parseInt(whole, 10).toString();

    if (useDigitSeparator) {
        const regex = new RegExp(`\\B(?=(\\d{${ns.digitGroups}})+(?!\\d))`, 'g');
        whole = whole.replace(regex, ns.digitSeparator);
    }

    const spacer = unit.trim() ? ' ' : '';
    const formattedNum = decimalPlaces > 0 ? `${whole}${ns.decimalSeparator}${decimal}` : whole;
    return unitPosition === "before" ? `${unit}${spacer}${formattedNum}` : `${formattedNum}${spacer}${unit}`;
}

function enforceCursorPosition(el) {
    let cursorPosition = el.value.length;
    if (unitPosition === "after") {
        cursorPosition -= (unit.length + 1);
    }
    el.setSelectionRange(cursorPosition, cursorPosition);
}

function handlePaste(e) {
    const pastedData = e.clipboardData.getData('text');
    let pastedRawValue = pastedData.replace(/[^0-9]/g, '');

    // Current content of the input without non-numeric characters
    let currentRawValue = inputElement.value.replace(/[^0-9]/g, '');

    // Remove leading zeroes from the current content
    currentRawValue = currentRawValue.replace(/^0+/, '');

    // Concatenate the current content with the pasted content
    let combinedValue = currentRawValue + pastedRawValue;

    // If the combined value exceeds 15 characters, remove characters from the end
    while (combinedValue.length > 15) {
        combinedValue = combinedValue.substring(0, combinedValue.length - 1);
    }

    const formattedValue = formatNumber(combinedValue);
    inputElement.value = formattedValue;
    e.preventDefault(); // Prevent the default paste operation.
    enforceCursorPosition(inputElement);
}

function inputHandler(e) {
    let targetValue = e ? e.target.value : inputElement.value;
    let rawValue = targetValue.replace(/[^0-9]/g, '');
    
    // Ensure rawValue doesn't exceed 15 characters
    if (rawValue.length > 15) {
        rawValue = rawValue.substring(0, 15);
    }

    const formattedValue = formatNumber(rawValue);

    if (e) {
        e.target.value = formattedValue;
        enforceCursorPosition(e.target);
    } else {
        inputElement.value = formattedValue;
    }
}

const inputElement = document.querySelector('.fixedDecimals');

inputElement.addEventListener('input', inputHandler);

inputElement.addEventListener('paste', handlePaste);

inputElement.addEventListener('keydown', (e) => {
    // Allow Command or Ctrl key combinations
    if (e.metaKey || e.ctrlKey) {
        return;
    }

    // Allow shift + arrow keys for text selection
    if (e.shiftKey && (e.key === 'ArrowLeft' || e.key === 'ArrowRight')) {
        return;
    }

    if (!(e.key.match(/[0-9]/) || e.key === 'Backspace')) {
        e.preventDefault();
    }
    setTimeout(() => enforceCursorPosition(e.target), 0);
});

inputElement.addEventListener('mouseup', (e) => {
    // If there's no selection, enforce cursor position
    if (inputElement.selectionStart === inputElement.selectionEnd) {
        enforceCursorPosition(e.target);
    }
});

// Update formatting based on the current settings
function updateFormatting() {
    inputElement.value = formatNumber(inputElement.value.replace(/[^0-9]/g, ''));
}

document.getElementById('decimalPlaces').addEventListener('change', (e) => {
    decimalPlaces = parseInt(e.target.value);
    updateFormatting();
});

document.getElementById('unit').addEventListener('keydown', (e) => {
    if (e.key.match(/[0-9]/)) {
        e.preventDefault();
    }
});

document.getElementById('unit').addEventListener('input', (e) => {
    unit = e.target.value;
    updateFormatting();
});

document.getElementById('unitPosition').addEventListener('change', (e) => {
    unitPosition = e.target.value;
    updateFormatting();
});

document.getElementById('useDigitSeparator').addEventListener('change', (e) => {
    useDigitSeparator = e.target.checked;
    updateFormatting();
});

document.getElementById('numberSystem').addEventListener('change', (e) => {
    numberSystem = parseInt(e.target.value);
    updateFormatting();
});

const unitInputElement = document.getElementById('unit');

let activeInput = ""; // A flag to keep track of which input is currently active

inputElement.addEventListener('focus', () => {
    activeInput = "main";
});

unitInputElement.addEventListener('focus', () => {
    activeInput = "unit";
});

inputElement.addEventListener('input', (e) => {
    if (activeInput !== "main") {
        return; // Exit early if the main input is not active
    }

    let targetValue = e ? e.target.value : inputElement.value;
    let rawValue = targetValue.replace(/[^0-9]/g, '');
    
    // Ensure rawValue doesn't exceed 15 characters
    if (rawValue.length > 15) {
        rawValue = rawValue.substring(0, 15);
    }

    const formattedValue = formatNumber(rawValue);

    if (e) {
        e.target.value = formattedValue;
        enforceCursorPosition(e.target);
    } else {
        inputElement.value = formattedValue;
    }
});

function initializeConfigVariables() {
    decimalPlaces = parseInt(document.getElementById('decimalPlaces').value);
    unit = document.getElementById('unit').value;
    unitPosition = document.getElementById('unitPosition').value;
    useDigitSeparator = document.getElementById('useDigitSeparator').checked;
    numberSystem = parseInt(document.getElementById('numberSystem').value);
}

document.addEventListener("DOMContentLoaded", function() {
    initializeConfigVariables();
    inputElement.value = formatNumber('0');
});

相关问题