动态添加输入时添加千位分隔符 javascript
Add thousand separator with javascript when add input dynamically
我在使用千位分隔符动态添加输入时遇到问题,
当我单击添加并出现输入表单时。
应该是当我输入数字时它会以千位分隔符排列。
请帮助我
$(document).ready(function(){
$(document).on('click', '.add', function(){
var html = '';
html += '<tr>';
html += '<td><input type="text" name="item_name[]" class="form-control inputnumber" onkeypress="return event.keyCode > 47 && event.keyCode < 58 || event.keyCode == 46" /></td>';
html += '</tr>';
$('#item_table').append(html);
});
$('input.inputnumber').keyup(function(event) {
if (event.which >= 37 && event.which <= 40) return;
$(this).val(function(index, value) {
return value
// Keep only digits and decimal points:
.replace(/[^\d.]/g, "")
// Remove duplicated decimal point, if one exists:
.replace(/^(\d*\.)(.*)\.(.*)$/, '')
// Keep only two digits past the decimal point:
.replace(/\.(\d{2})\d+/, '.')
// Add thousands separators:
.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="table-repsonsive">
<table class="table table-bordered" id="item_table">
<tr>
<th><button type="button" name="add" class="btn btn-success btn-sm add">ADD</button></th>
</tr>
</table>
</div>
您可以使用 NumberFormat 对象
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat
$(document).ready(function() {
$(document).on('click', '.add', function() {
var html = '';
html += '<tr>';
html += '<td><input type="text" name="item_name[]" class="form-control inputnumber" ></td>';
html += '</tr>';
$('#item_table').append(html);
});
$('#item_table').change(function(event) {
if (event.target.classList.contains("inputnumber")) {
// remove any commas from earlier formatting
const value = event.target.value.replace(/,/g, '');
// try to convert to an integer
const parsed = parseInt(value);
// check if the integer conversion worked and matches the expected value
if (!isNaN(parsed) && parsed == value) {
// update the value
event.target.value = new Intl.NumberFormat('en-US').format(value);
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="table-repsonsive">
<table class="table table-bordered" id="item_table">
<tr>
<th><button type="button" name="add" class="btn btn-success btn-sm add">ADD</button></th>
</tr>
</table>
</div>
我会使用 Intl.NumberFormat()
构造函数。您可以在此处找到文档和所有不同的选项:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat
在下面的代码片段中,您会看到格式在您键入时发生变化。如果您添加文本,它只会删除文本。如果你加上第二位小数,它一开始不会做任何事情
我已经忘记了我曾经知道的大部分 jQuery,所以我用 Vanilla JS 编写了代码片段。我在每一行都添加了注释来解释该步骤。
const table = document.querySelector(`#item_table`);
// Add an event listener to the button in the form
table.querySelector(`button`).addEventListener(`click`, function() {
// Create a <tr> element
const tr = document.createElement(`tr`);
// Create a <td> element
const td = document.createElement(`td`);
// Create an <input> element
const inpt = document.createElement(`input`);
// Add the input attributes
inpt.type = `text`;
inpt.classList.add(`form-control`);
inpt.classList.add(`inputnumber`);
// Add an event listener to the input element
inpt.addEventListener(`keyup`, function(event) {
// Current string value of the input
const value = this.value;
// Split the value string into an array on each decimal and
// count the number of elements in the array
const decimalCount = value.split(`.`).length - 1;
// Don't do anything if a first decimal is entered
if (event.key === `.` && decimalCount === 1) return
// Remove any commas from the string and convert to a float
// This will remove any non digit characters and second decimals
const numericVal = parseFloat(value.replace(/,/g, ''));
//NumberFormat options
const options = {
style: `decimal`,
maximumFractionDigits: 20,
};
// Assign the formatted number to the input box
this.value = new Intl.NumberFormat(`en-US`, options).format(numericVal);
})
// Append the input to the td
td.append(inpt);
// Append the td to the tr
tr.append(td);
// Append the tr to the table
table.append(tr);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="table-repsonsive">
<table class="table table-bordered" id="item_table">
<tr>
<th><button type="button" name="add" class="btn btn-success btn-sm add">ADD</button></th>
</tr>
</table>
</div>
我在使用千位分隔符动态添加输入时遇到问题, 当我单击添加并出现输入表单时。 应该是当我输入数字时它会以千位分隔符排列。 请帮助我
$(document).ready(function(){
$(document).on('click', '.add', function(){
var html = '';
html += '<tr>';
html += '<td><input type="text" name="item_name[]" class="form-control inputnumber" onkeypress="return event.keyCode > 47 && event.keyCode < 58 || event.keyCode == 46" /></td>';
html += '</tr>';
$('#item_table').append(html);
});
$('input.inputnumber').keyup(function(event) {
if (event.which >= 37 && event.which <= 40) return;
$(this).val(function(index, value) {
return value
// Keep only digits and decimal points:
.replace(/[^\d.]/g, "")
// Remove duplicated decimal point, if one exists:
.replace(/^(\d*\.)(.*)\.(.*)$/, '')
// Keep only two digits past the decimal point:
.replace(/\.(\d{2})\d+/, '.')
// Add thousands separators:
.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="table-repsonsive">
<table class="table table-bordered" id="item_table">
<tr>
<th><button type="button" name="add" class="btn btn-success btn-sm add">ADD</button></th>
</tr>
</table>
</div>
您可以使用 NumberFormat 对象
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat
$(document).ready(function() {
$(document).on('click', '.add', function() {
var html = '';
html += '<tr>';
html += '<td><input type="text" name="item_name[]" class="form-control inputnumber" ></td>';
html += '</tr>';
$('#item_table').append(html);
});
$('#item_table').change(function(event) {
if (event.target.classList.contains("inputnumber")) {
// remove any commas from earlier formatting
const value = event.target.value.replace(/,/g, '');
// try to convert to an integer
const parsed = parseInt(value);
// check if the integer conversion worked and matches the expected value
if (!isNaN(parsed) && parsed == value) {
// update the value
event.target.value = new Intl.NumberFormat('en-US').format(value);
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="table-repsonsive">
<table class="table table-bordered" id="item_table">
<tr>
<th><button type="button" name="add" class="btn btn-success btn-sm add">ADD</button></th>
</tr>
</table>
</div>
我会使用 Intl.NumberFormat()
构造函数。您可以在此处找到文档和所有不同的选项:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat
在下面的代码片段中,您会看到格式在您键入时发生变化。如果您添加文本,它只会删除文本。如果你加上第二位小数,它一开始不会做任何事情 我已经忘记了我曾经知道的大部分 jQuery,所以我用 Vanilla JS 编写了代码片段。我在每一行都添加了注释来解释该步骤。
const table = document.querySelector(`#item_table`);
// Add an event listener to the button in the form
table.querySelector(`button`).addEventListener(`click`, function() {
// Create a <tr> element
const tr = document.createElement(`tr`);
// Create a <td> element
const td = document.createElement(`td`);
// Create an <input> element
const inpt = document.createElement(`input`);
// Add the input attributes
inpt.type = `text`;
inpt.classList.add(`form-control`);
inpt.classList.add(`inputnumber`);
// Add an event listener to the input element
inpt.addEventListener(`keyup`, function(event) {
// Current string value of the input
const value = this.value;
// Split the value string into an array on each decimal and
// count the number of elements in the array
const decimalCount = value.split(`.`).length - 1;
// Don't do anything if a first decimal is entered
if (event.key === `.` && decimalCount === 1) return
// Remove any commas from the string and convert to a float
// This will remove any non digit characters and second decimals
const numericVal = parseFloat(value.replace(/,/g, ''));
//NumberFormat options
const options = {
style: `decimal`,
maximumFractionDigits: 20,
};
// Assign the formatted number to the input box
this.value = new Intl.NumberFormat(`en-US`, options).format(numericVal);
})
// Append the input to the td
td.append(inpt);
// Append the td to the tr
tr.append(td);
// Append the tr to the table
table.append(tr);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="table-repsonsive">
<table class="table table-bordered" id="item_table">
<tr>
<th><button type="button" name="add" class="btn btn-success btn-sm add">ADD</button></th>
</tr>
</table>
</div>