I'm having trouble finding the jquery checkbox function to get the ID based on the largest data. The selected data, of course, is clicked and checked, not unchecked.
HTML:
<input type="checkbox" class="checkbox" name="id[]" data-id="001" data-weight="10" value="001"/> A (10 kg) <br>
<input type="checkbox" class="checkbox" name="id[]" data-id="002" data-weight="20" value="002"/> B (20 kg) <br>
<input type="checkbox" class="checkbox" name="id[]" data-id="003" data-weight="30" value="003"/> C (30 kg) <br>
<input type="checkbox" class="checkbox" name="id[]" data-id="004" data-weight="40" value="004"/> D (40 kg) <br>
<br>
<br>
<div>Heaviest Weight</div>
<input type="text" id="getWeight">
<div>ID the Heaviest Weight</div>
<input type="text" id="getId"><br>
Javascript:
$(document).ready(function() {
var maximum = null;
$(".checkbox").click(function(){
var value = $(this).data('weight');
maximum = (value > maximum) ? value : maximum;
id = $(this).data('id');
$('#getId').val(id);
$('#getWeight').val(maximum);
});
});
Try looping all checked
checkbox, and compare each weight, every change of each checkbox.
$(document).ready(function() {
$(".checkbox").change(function(){
var checkboxes = document.querySelectorAll(".checkbox:checked");
var maximum = 0;
var maximumID = 0;
checkboxes.forEach(checkbox => {
var value = $(checkbox).data('weight');
if( value > maximum ){
maximum = value;
maximumID = $(checkbox).data('id');
}
});
$('#getId').val(maximumID);
$('#getWeight').val(maximum);
});
});