Jquery 复选框功能根据最大数据获取ID

Jquery checkbox function get ID based on biggest data

我找不到 jquery 复选框函数以根据最大数据获取 ID。选中的数据,当然是点击勾选的,不是不勾选的。

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);

  });
});

https://codepen.io/andreasdan/pen/MWvVypm

尝试循环所有 checked 复选框,并比较每个权重,每个复选框的每个变化。

$(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);
  });
    
});