私はユーザーに各製品の入力フィールドを含む特定の製品にドル金額を追加させようとしています。トリッキーな部分は、すべてのフィールドの合計がアカウントの残高を超えることはできません。入力フィールドの合計は勘定残高を超えることはできません
すべての入力フィールドが残高以上であるかどうかを検出し、残高以上の残高を持つ入力フィールドを設定する方法を理解できないようです。または、残りの残高がすでにゼロである場合、入力フィールドに入力された数値はゼロに切り替わり、アクションは発生しません。
ここでJSFiddleを作成しました。 https://jsfiddle.net/12agemfe/1/
var qty = $('input[type=text]');
var accountbalance = parseInt($('#accountbalance').text());
var removebalance;
var newbalance;
$('input').on('focusout', function() {
//set removebalance to zero each time
removebalance = 0;
//get total from all input fields
$(qty).each(function() {
removebalance += parseFloat($(this).val());
});
//set current balance
newbalance = (parseFloat(accountbalance).toFixed(2)
- parseFloat(removebalance).toFixed(2));
//Needs to set input to zero and not update #accountbalance
//if entering more than #account balance
//Needs to correct input value if entered more than remaining balance
if (newbalance < 0) {
alert('You Can Not Cash out more than your Balance!');
return false;
}
//once input fields are totaled, update the balance on the screen
//should not allow negative balance and needs two decimal points
// parseFloat.fixedTo(2)
$('#accountbalance').text(newbalance);
});
//Cant submit if input is more than balance
$('input[type=submit]').click(function() {
if (newbalance < 0) {
alert('You Can Not Cash out more than your Balance!');
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" name="value[]" value="0.00">
<input type="text" name="value[]" value="0.00">
<input type="text" name="value[]" value="0.00">
<input type="text" name="value[]" value="0.00">
<input type="text" name="value[]" value="0.00">
</form>
<div id="accountbalance">500</div>
<button id="submit">Submit</button>
しかし、ときにJSを引く、それはその良い練習そのけど、その真とにかく –
LucasKot-Zaniewskiのイー@しかし、このような状況のタイプではありません:-)タイプに来るときあなたのための思考を行いますコンバージョンは結果を変更します。 –
ここで関連性のある例を挙げていただけますか? –