#javascript #jquery
#javascript #jquery
Вопрос:
Я пытаюсь заставить пользователей добавлять суммы в долларах к определенным продуктам, которые содержат поля ввода для каждого продукта. Сложность заключается в том, что сумма всех полей не может превышать баланс их учетной записи.
Кажется, я не могу понять, как определить, все ли поля ввода больше, чем баланс, а затем установить поле ввода, в котором больше баланса, на оставшийся баланс. Или, если там остаток средств уже равен нулю, тогда число, введенное в поле ввода, переключится на ноль / никаких действий не будет.
Я создал 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>
Ответ №1:
Я немного изменил сценарий в fork из вашего jsfiddle. Вот оно — https://jsfiddle.net/xqhnyf0k/2 /
Наиболее важные изменения связаны с последствиями newbalance ниже 0. В такой ситуации мы должны изменить входное значение на значение- (значение ниже 0).
if (newbalance < 0) {
alert('You Can Not Cash out more than your Balance!');
//my code
$('#accountbalance').text("0.00"); //set 0 in balance UI
$(this).val(parseFloat(parseFloat($(this).val()) newbalance).toFixed(2)); //set currently changing input val to val newbalance so if balance is minus it will left only possible amount
//end of my code
return false;
}
Другие изменения связаны с исправлением преобразования в операции с плавающей запятой и с плавающей запятой. Пример из:
newbalance = (parseFloat(accountbalance).toFixed(2)
- parseFloat(removebalance).toFixed(2));
Для
newbalance = (parseFloat(accountbalance) - parseFloat(removebalance));
Изменение важно, потому что toFixed(http://www.w3schools.com/jsref/jsref_tofixed.asp ) преобразует число в строку, так что вы выполняете операцию со строками, а не с числами. Метод toFixed следует использовать только для представления.
Комментарии:
1. Но когда вы вычитаете, js думает за вас, когда дело доходит до типов 🙂 не то, чтобы это была хорошая практика, но в любом случае это правда
2. @LucasKot-Zaniewski да, но в этой ситуации преобразование типов изменит результат.
3. Не могли бы вы привести пример, который был бы уместен здесь?
4. @LucasKot-Zaniewski хорошо, проверьте любую операцию с плавающей запятой, например, вставьте в консоль: (parseFloat(12.955).toFixed(2) — parseFloat(11.950).toFixed(2)); и (parseFloat(12.955) — parseFloat(11.950)); . Второй результат верен.
5. Да, но я рекомендую выполнять операции с числами, а не со строками. Это более понятно в коде.
Ответ №2:
Я сделал то, что, как я думаю, вы хотите от этого скрипта.
Посмотрите.
var qty = $('input[type=text]');
var accountbalance = parseInt($('#accountbalance').text());
var removebalance;
var newbalance;
var inputCounter = 0; // zero-based
$('input').on('focusout', function() {
//set removebalance to zero each time
removebalance = 0;
//check number iput and die if letters or negative number
if (!$.isNumeric($(this).val()) || $(this).val() < 0) {
$(this).val(0);
return false;
}
//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));
$('#accountbalance').text(newbalance.toFixed(2));
//Needs to set input to zero and not update #accountbalance
//if entering more than #account balance
if (newbalance < 0) {
//alert('You Can Not Cash out more than your Balance!');
return false;
}
// Set values to fixed on focusout
thisValtoFixed = parseFloat($(this).val()).toFixed(2);
$(this).val(thisValtoFixed);
});
//Cant submit if input is more than balance
$('#submit').click(function() {
if (newbalance < 0) {
//alert('You Can Not Cash out more than your Balance!');
// Correcting last input
$(qty).each(function() {
var tempAmount = parseFloat($(this).val());
if (tempAmount > 0) {
$(this).val(tempAmount.toFixed(2));
inputCounter ;
}
});
// set corrected value
var lastInputAmount = parseFloat($(qty).eq(inputCounter - 1).val());
var correctedInputValue = lastInputAmount newbalance;
$(qty).eq(inputCounter - 1).val(correctedInputValue.toFixed(2));
alert('You Can Not Cash out more than your Balance!nnWe corrected your last amount to ' correctedInputValue.toFixed(2));
// Show a zero balance
$('#accountbalance').text(0.00);
newbalance = 0;
// Change the submit button for "Submit like this?"
$("#submit").text("Submit like this?");
return false;
}else{
// Ok to submit!!
alert("Submitted.");
}
});
input {
display: block;
margin-bottom: 5px;
}
<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.00</div>
<button id="submit">Submit</button>