我已经建立了这个简单的租金负担能力的java脚本计算器,我有的问题是“Rent Affordability TextBox”有时可以返回的最后一个框 - (负数)我试图将该值设置为0.00如果数字变为负
我已将此添加到我的脚本中:
if (RentAffordability < 0) RentAffordability = 0.00;
没有运气。这是完整的代码:
<html lang="en-us">
<head></head>
<body>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
function run() {
var PercentageRate = 40;
var Income = parseInt(document.getElementById('YearlyIncome').value);
var Expenses = parseInt(document.getElementById('MonthlyExpenses').value);
var PercentageCalculated = Income / PercentageRate;
//document.getElementById('RentAffordability').value = PercentageCalculated - Expenses;
$('#RentAffordability').val((PercentageCalculated - Expenses).toFixed(2));
}
if (RentAffordability < 0)
RentAffordability = 0.00;
</script>
<script>
(function($) {
$.fn.currencyInput = function() {
this.each(function() {
var wrapper = $("<div class='currency-input' />");
$(this).wrap(wrapper);
$(this).change(function() {
var min = parseFloat($(this).attr("min"));
var max = parseFloat($(this).attr("max"));
var value = this.valueAsNumber;
if (value < min)
value = min;
else if (value > max)
value = max;
$(this).val(value.toFixed(2));
});
});
};
})(jQuery);
$(document).ready(function() {
$('input.currency').currencyInput();
});
</script>
<table border="0" cellpadding="2" cellspacing="2">
<tbody>
<tr>
<td>Combined Annual Income: </td>
<td><input type="number" class="currency textBox" name="YearlyIncome" id="YearlyIncome" value="0.00" /></td>
</tr>
<tr>
<td>Combined Monthly Expenses:</td>
<td><input type="number" class="currency textBox" name="MonthlyExpenses" id="MonthlyExpenses" value="0.00" /></td>
</tr>
<tr>
<td colspan="2" rowspan="1"> </td>
</tr>
<tr>
<td>Your Rent Affordability:</td>
<td><input type="number" class="currency textBox" name="RentAffordability" id="RentAffordability" /></td>
</tr>
<tr>
<td colspan="2" rowspan="1"> </td>
</tr>
<tr>
<td colspan="2" rowspan="1" style="padding-left: 250px;"><button onclick="run()">Calculate Your Rent</button></td>
</tr>
</tbody>
</table>
</body>
</html>
答案 0 :(得分:1)
使用RentAffordability = Math.max(0, RentAffordability)
获取更大的0或RentAffordability的当前值。
当RentAffordability为负时,它会回落到0
答案 1 :(得分:0)
我找到的一些问题
更新代码应该是这样的:
function run() {
var PercentageRate = 40;
var Income = parseInt(document.getElementById('YearlyIncome').value);
var Expenses = parseInt(document.getElementById('MonthlyExpenses').value);
var PercentageCalculated = Income / PercentageRate;
var RentAffordability = PercentageCalculated - Expenses
if (RentAffordability < 0)
RentAffordability = 0.00;
$('#RentAffordability').val((RentAffordability).toFixed(2));
}