I have multiple range sliders in a Gravity Form. I want to calculate the totals of the user’s choices and display on screen. The jQuery works and does what it should.
However I need the initial values of each slider to be zero and then stop them going over a total of 100, but if I use jQuery to set the initial value of each slider to zero with $('.slider').val(0)
as suggested elsewhere, the value of #total remains always zero. How can I set initial values to zero and still get #total to display the sum of all slider values?
$('.slider').on('change', function() {
var sum = 0;
$('.slider').each(function() {
sum += isNaN(this.value) || $.trim(this.value) === '' ? 0 : parseFloat(this.value);
});
$('#total').text(sum);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="total"></p>
<input name="input_1" id="input_1_1" type="number" step="1" min="0" max="100" value="50" class="slider" />
<input name="input_2" id="input_1_2" type="number" step="1" min="0" max="100" value="50" class="slider" />
<input name="input_3" id="input_1_3" type="number" step="1" min="0" max="100" value="50" class="slider" />
2
Answers
You can set the initial value of the number field to 0 using the Default Value under the Advanced Tab of the field in Gravity Forms
Not sure how the sliders are related, but
type="range"
if you need "sliders".reduce()
to reduce a list (array or collection) to a different type (Number) in your caseMath.min()
to cap your value to a max of100
Even with this solution (since you did not explained what are you actually after) it’s a bad UX to let the user slide something uselessly – seeing a value result unchanged at 100. I’ll leave it up to you to figure out the actual UI requirements.