Use jQuery input mask for a ratios?

I'm using this jquery input mask plugin to try and create an input field where the user can enter a ratio that adds up to 100%. E.g. 10% / 90%

<input type="text" class="form-control" id="input" data-inputmask="'mask': '99/99', placeholder="50/50">

Both parts of the input must add up to 100. So if the user types 20, then on the right, the number should be 80 e.g. 20/80. If the number 80 is changed to 40, then the number 20 on the left should automatically be changed to 60. It shouldn't let you put in a number over 100.

This is my attempt so far but it's not working as expected. I'm unsure of how to create an if() statement around whether the user is editing the left side or the right. I only want the left value to change, if the right value is being edited and vice versa. Without this, my code will just replace the both sides of the ratio.

$('#input').keyup(function(){
    var user_ratio = $(this).val().split('/');
    var left = 100 - parseInt(user_ratio[1]); //65
    var right = 100 - parseInt(user_ratio[0]); //35
    var $(this).val(left+'/'+right);
});

Any suggestion?

Answers 1

  • You should store previous value somehow. Here just an idea that need to be developed. Also if designer is understanding person, I would probably use two inputs with "%" as a label for such purposes (it's mush simpler and more stable)

    $('#input').val('99%/99%') // for demo
    
    function arrayFromValue(val) {
      return val.split('/').map(function(str) {return isNaN(parseInt(str)) ? 0 : parseInt(str)});
    }
    
    var $input = $('#input'), 
        currentValue = arrayFromValue( $input.val() );
    
    $input.on('keyup', function() {
        var ratio = arrayFromValue( $(this).val() );
        
        // if the same value return
        if(currentValue[0] === ratio[0] && currentValue[1] === ratio[1]) return;
        
        // if more than 100 return with previous value
        if(ratio[0] > 100 || ratio[1] > 100) {
          return $(this).val(currentValue[0] + '%/' + currentValue[1] + '%');
        }
        
        var left = currentValue[1] !== ratio[1] ? 100 - ratio[1] : ratio[0];
        var right = currentValue[0] !== ratio[0] ? 100 - ratio[0] : ratio[1];
    
        currentValue = [left, right];
        $(this).val(left + '%/' + right + '%');
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input id="input" type="text" />


Related Articles