I am trying to calculate the average for a given subjects and to print the average directly whenever the user change a value.
I am using an input fields to input the marks and a corresponding select options for the hours to each subject. I can do it correctly for one subject but when I add the class 'subject' to other divs. I can't figure how to do the same thing without mixing the subject values.
Part of my HTML code :
<!-- Fourth Subject -->
<div class="form-row text-center subject">
<div class="col-4 ">
<input type="text" name="mark4" class="form-control text-center mark" placeholder="العلامة">
</div>
<!--<div class="col-3">
<input type="text" class="form-control text-center" placeholder="State">
</div>-->
<select id="select" name="option4" class="custom-select col-4 text-center hours" id="inlineFormCustomSelect">
<option selected>عدد الساعات</option>
<option value="1">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<div class="col-4">
<input type="text" name='subject4' class="form-control text-center" placeholder="إسم المادة">
</div>
</div>
<!-- End of Fourth Subject -->
</br>
<!-- Fifth Subject -->
<div class="form-row text-center subject">
<div class="col-4 ">
<input type="text" name="mark5" class="form-control text-center mark" placeholder="العلامة">
</div>
<!--<div class="col-3">
<input type="text" class="form-control text-center" placeholder="State">
</div>-->
<select id="select" name="option5" class="custom-select col-4 text-center hours" id="inlineFormCustomSelect">
<option selected>عدد الساعات</option>
<option value="1">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<div class="col-4">
<input type="text" name='subject5' class="form-control text-center" placeholder="إسم المادة">
</div>
</div>
<!-- End of Fifth Subject -->
And here is how I get the values for one subject using jQuery:
$('.subject').keyup(function () {
var mark = 0;
var hours = 0;
$('.mark').change(function() {
mark = Number($(this).val());
console.log('mark is ' + mark);
hours = $('select[name=option5]').val();
$(".hours").change(function() {
hours = $('select[name=option5]').val();
console.log('hours are ' + hours);
});
$('#avg').val(mark*hours);
});
$(".hours").change(function() {
hours = $('select[name=option5]').val();
console.log('hours are ' + hours);
$('.mark').each(function() {
mark = Number($(this).val());
console.log('mark is ' + mark);
$('#avg').val(mark*hours);
});
});
});
the avg should be (mark1 * hours_for_mark1 + mark2 * hours_for_mark_2) / number_of_hours. Is there any way to do it using jQuery ? or even a better structure !?