joshw50886526 wrote One difference is I wish the total would calculate without having to click a button. Is it possible to have it calculate once the user clicks or tabs out of a field? Is this on-blur?' |
Yes, you would use the jquery blur function instead of the click function, as the example code below shows: (I've streamed lined the jquery code a bit so you can add as many 'fields' or as little as needed without having to add them to the jquery code.
So if you require extra fields just assign the next sequential number to the form field:
<input type="text" name="field_5" id="field_5" class="field field_5">
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Calculate Form Fields</title>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function(){
$('.field').blur(function(){
var field_1 = $('.field_1').val();
$(".field_1").val(field_1);
// Check field_1 is not empty
if(field_1 === "") {
alert("Please fill in field 1");
}
var count_fields = $('.field').length;
var i = 1;
total = 0;
// Loop through fields
while(i <= count_fields) {
sub_total = $('.field_' + i).val();
total = +total + +sub_total;
$('.field_' + i).val(sub_total);
i++;
}
// Write total to page
$('.total span').text(total);
});
// Clear fields
$('.clear').css('cursor' , 'pointer').click(function(){
var count_fields = $('.field').length;
var i = 1;
while(i <= count_fields) {
$('.field_' + i).val("");
i++;
}
$(".total span").text("0");
});
});
</script>
</head>
<body>
<p>
<label for="field_1">Field 1</label>
<input type="text" name="field_1" id="field_1" class="field field_1">
</p>
<p>
<label for="field_2">Field 2</label>
<input type="text" name="field_2" id="field_2" class="field field_2">
</p>
<p>
<label for="field_3">Field 3</label>
<input type="text" name="field_3" id="field_3" class="field field_3">
</p>
<p>
<label for="field_4">Field 4</label>
<input type="text" name="field_4" id="field_4" class="field field_4">
</p>
<p>
<input type="submit" name="submit" class="clear" value="Clear">
</p>
<div class="total">Total <span>0</span></div>
</body>
</html>