Add a class if var < 0 jquery

Add a class if var < 0 jquery

本文关键字:lt jquery var class if Add      更新时间:2023-09-26

我不知道自己做错了什么。由于某些原因,我无法使用JS将此类添加到#总权重中。CSS很好,因为我已经硬编码并且正在工作。这个总数也很完美。

/**********这是我的HTML**************/

<tr id="results">
    <td>Grade (%)</td>
    <td><input type="text" value="" id="final-grade" name="final-grade"></td>
    <td><input type="text" value="100" id="total-weight" name="total-weight"><span><small> remaining (%)</small></span></td>
</tr>

/********这是我的JS***************/

'use strict';
$(document).on('keyup', '.weight-value', function() {
    // the sum of weight (%)
    var sumWeight = 0;
    var totalWeight = 0;
    $('.weight-value').each(function(){
        sumWeight += +$(this).val();
    });// end of sum of weight (%)
    // populate weigth remaining
    totalWeight = $('#total-weight').val(100 - sumWeight);
        if(totalWeight < 0) {
            $('#total-weight').addClass('table-border');
        }
});// end document .on keyup

$('#total-weight').val(100 - sumWeight)将设置元素的值并返回一个jQuery对象。所以你的情况不会起作用。

此外,您可能希望使用toggleClass(),因为如果值>=0 ,您希望删除该类

'use strict';
$(document).on('keyup', '.weight-value', function () {
    // the sum of weight (%)
    var sumWeight = 0;
    var totalWeight = 0;
    $('.weight-value').each(function () {
        sumWeight += +$(this).val();
    }); // end of sum of weight (%)
    // populate weigth remaining
    totalWeight = 100 - sumWeight;
    $('#total-weight').val(totalWeight);
    $('#total-weight').toggleClass('table-border', totalWeight < 0);
}); // end document .on keyup

演示:Fiddle