Reputation: 175
I have 2 input values, both with a 30 integer max. Their values are added together and attached to the "results" class.
However, I want to change the value of an input to "1" when the value is less than 5, with the original value remaining in the input box, and the new value attached to ".results", while still maintaining the addition factor with ".results".
HTML
<div class="section">
<input type="number" class="chicken" min="0" max="30"/>
<input type="number" class="turkey" min="0" max="30"/>
</div>
<p class="results"></p>
jQuery
$(document).on("keyup", "input", function() {
var chicken = parseInt($('.chicken').val(), 10);
var turkey = parseInt($('.turkey').val(), 10);
if (chicken < 5) {
$(sum).val(2);
}
$("input").each(function(){
sum += +$(this).val();
});
$(".results").html(sum);
});
Upvotes: 1
Views: 44
Reputation: 4755
You just need to check against values when you loop through elements.
If any of them is less than 5
, then you add 1
to sum
value instead of real value. Otherwise you use real values.
$(document).on("keyup", "input", function() {
var sum = 0;
var chicken = parseInt($('.chicken').val(), 10);
var turkey = parseInt($('.turkey').val(), 10);
$("input").each(function(){
if($(this).val() < 5)
{
sum === 1 ? sum : sum++;
}
else
{
sum += +$(this).val();
}
});
$(".results").html(sum);
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div class="section">
<input type="number" class="chicken" min="0" max="30"/>
<input type="number" class="turkey" min="0" max="30"/>
</div>
<p class="results"></p>
</body>
</html>
Upvotes: 1