JSFiddle - React, Tailwind, and code Playground

by XGundam05

HTML

<div id="inputs" class="control-group">
    Input 1: <input type="text" class="num"></input><br />
    Input 2: <input type="text" class="num"></input><br />
    Input 3: <input type="text" class="num"></input><br />
    Input 4: <input type="text" class="num"></input><br />
    Input 5: <input type="text" class="num"></input><br />
    Input 6: <input type="text" class="num"></input><br />
    Input 7: <input type="text" class="num"></input><br />
    Input 8: <input type="text" class="num"></input><br />
    Input 9: <input type="text" class="num"></input><br />
</div>
<div id="barOuter">
    <div id="barInner"></div>
    <div id="percent">0%</div>
</div>
<input type="button" value="Submit" id="percentBtn" disabled="true" />

CSS

.invalid{
    background-color: red;
}
#percentBtn{
    width:100px;
}
#barOuter{
    width: 200px;
    border: solid 1px black;
    height: 1.1em;
    position: relative;
    overflow: hidden;
}
#barInner{
    width: 0%;
    height: 100%;
    background-color: green;
    position: absolute;
    top: 0px;
    left: 0px;
}
#percent{
    position: absolute;
    z-index: 10;
    top: 0px;
    width: 100%;
    text-align: center;
}

JavaScript

$(document).on('keyup', 'input.num', function (e) {
    var _val = $(this).val() * 1;
    
    if(!isNaN(_val) && _val <= 100)
        $(this).removeClass('invalid');
    else
        $(this).addClass('invalid');
    
    var _total = _checkInputs(this);
    _disableInputs(_total);
});

function _checkInputs(_this){
    var _tVal = $(_this).val() * 1;
    var _total = 0
    
    $('input.num:not(.invalid)').each(function(){
        if(this !== _this)
            _total += $(this).val() * 1;
    });
    
    if(!isNaN(_tVal)){
        if(_total + _tVal > 100)
            $(_this).addClass('invalid');
        else
            _total += _tVal;
    }
    
    $('#percent').text(_total + '%');
    $('#barInner').width(_total + '%');
    
    return _total;
}

function _disableInputs(_total){    
    $('input.num').each(function(){
        if($(this).hasClass('invalid') || $(this).val() === '')
            $(this).prop('disabled', _total == 100);
        $('#percentBtn').prop('disabled', !(_total == 100));
    });
}