我正在做一个函数。一旦用户开始输入数字,JavaScript函数就开始格式化输入文本字段。到目前为止还不错。但是,当我试图取这个值来执行一个简单的计算时,我得到了一个错误。我猜想,这是由于逗号的缘故。那么,在将输入解析为计算时,我可以从输入中删除这些逗号吗?一旦值被计算出来。我想把它以逗号格式显示为输出(Annual Salary)。
$('input.number').keyup(function(event) {
// skip for arrow keys
if (event.which >= 37 && event.which <= 40) return;
// format number
$(this).val(function(index, value) {
return value
.replace(/D/g, "")
.replace(/B(?=(d{3})+(?!d))/g, ",");
});
});
function calculateSalary() {
var salary = document.getElementById("salary").value;
var years = document.getElementById("years").value;
var annumSalary = salary * years;
document.getElementById("annumSalary").value = Math.round(annumSalary);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<label>Salary</label>
<input class="form-control number" name="salary" id="salary" required/>
<br>
<label>Years</label>
<input class="form-control" name="years" id="years" value="" type="number" required/>
<br>
<label>Annual Salary</label>
<input class="form-control number" name="annumSalary" id="annumSalary" value="" type="number" readonly/>
<br>
<input type="submit" name="calculate" id="calculate" value="Calculate" onClick="calculateSalary()" />
删除字符串中的逗号并将字符串转换为数字:
const str = '123,456.78';
const num = parseFloat(str.replace(/,/g, ''));
转换回带逗号的字符串:
const formatted = new Intl.NumberFormat().format(num);
老兄,只要加上parseInt()
当你得到document.getElementById('salary').value
的值时如果你认为用户将输入小数,使用parseFloat。
通常parseInt()和parseFloat()将字符串转换为数字转义(常见的)内容,如(,.etc)
PS:另外,如果你使用jQuery,使用$('#salary')。值,使其看起来简单。
$('input.number').keyup(function(event) {
// skip for arrow keys
if (event.which >= 37 && event.which <= 40) return;
// format number
$(this).val(function(index, value) {
return value
.replace(/D/g, "")
.replace(/B(?=(d{3})+(?!d))/g, ",");
});
});
function calculateSalary() {
var salary = parseInt(document.getElementById("salary").value);
var years = parseInt(document.getElementById("years").value);
var annumSalary = salary * years;
document.getElementById("annumSalary").value = Math.round(annumSalary);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<label>Salary</label>
<input class="form-control number" name="salary" id="salary" required/>
<br>
<label>Years</label>
<input class="form-control" name="years" id="years" value="" type="number" required/>
<br>
<label>Annual Salary</label>
<input class="form-control number" name="annumSalary" id="annumSalary" value="" type="number" readonly/>
<br>
<input type="submit" name="calculate" id="calculate" value="Calculate" onClick="calculateSalary()" />