1
我有一種模式,允許用戶通過填寫表格填寫表格,在表格中輸入要添加的燃油量,但最大燃油量爲180升,所以如果現有的燃料是170升(現有的燃料價值將從數據庫中檢索),並且用戶試圖增加20升,則應該產生錯誤。我已經有了一些代碼,但它不會產生錯誤。如果有人能指出這個問題,將不勝感激。JavaScript - 獲取用戶輸入並用於計算以驗證值
$(document).ready(function() {
$('#fuel').blur(function() {
if (!ValidateFuel()) {
e.preventDefault();
}
});
$('#auth_form8').on('submit', function(e) {
if (!ValidateFuel()) {
e.preventDefault();
}
});
});
function ValidateFuel() {
var IsValid = false;
var fuel_to_add = $('#fuel').val();
var current_fuel = '100'; // this value will be retrieved from database
var fuel_once_added = Number(current_fuel) + Number(fuel_to_add);
if (fuel_once_added > 180) {
$('#alertInvalidFuel').show();
IsValid = false;
} else {
$('#alertInvalidFuel').hide();
IsValid = true;
}
return IsValid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="btn btn-success" role="button" data-target="#confirm-refuelG-EEGU" data-toggle="modal"><em class='fa fa-plus'></em></a>
<div id="confirm-refuelG-EEGU" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add Fuel G-EEGU</h4>
</div>
<div class="modal-body">
<form name="auth_form8" id="auth_form8" method="post" action="action_refuel.php">
<p>This action cannot be undone.</p>
<hr>
<input class="form-control" id="aircraft_id" name="aircraft_id" value='1' type="hidden">
<div class="form-group" name="fuel" id="fuel">
<label for="auth_code8" class="control-label">
Fuel to add:</label>
<input class="form-control" id="fuel" name="fuel" type="number" required>
</div>
<div style="display:none;" class="alert alert-danger" id="alertInvalidFuel">
<p>Fuel will exceed 180 litres.</p>
</div>
<hr>
<div class="form-group has-feedback" name="auth_code8" id="auth_code8">
<label for="auth_code8" class="control-label">
Authorisation Code</label>
<input class="form-control" id="auth_code_input8" autocomplete="new-password" name="refuel_auth_code" type="password" required>
<span class="form-control-feedback glyphicon" id="iconBad8"></span>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" id="submit" class="btn btn-success">Add Fuel</button>
</div>
</form>
</div>
</div>
</div>
'e'未定義。它應該是'$('#fuel')。blur(function(e){!ValidateFuel()){e.preventDefault(); } });'。使用[瀏覽器控制檯(開發工具)](http://webmasters.stackexchange.com/q/8525)(點擊'F12')並讀取任何錯誤。使用[JSHint](http://jshint.com/)立即查找代碼問題。 – Xufox
@Xufox不幸的是,這並不能解決問題。在JSHint或控制檯上沒有顯示錯誤。我認爲這只是不觸發驗證功能? – sinesine
@Xufox說了什麼,而且你的html格式不好。 –