Search code examples
javascriptjqueryeventskeyup

Jquery - keyup event checking input value in three fields


I'm looking for a form validation solution. I have three number fields. 1st of them have values: min=50, max=100. 2nd and 3rd TOGETHER will have max=50 but it cant be split in same way, so max=25. I thought of using IF statements, but that solution will be too complicated. How it should work:

  • 1st input value=50, 2nd value=25, 3rd value=25,
  • 1st input value=60, 2nd value=0, 3rd value=50,
  • 1st input value=75, 2nd value=20, 3rd value=5,
  • etc

I have some code to validate proper data input:

$(document).ready(function () {    

    $('input').keyup(function() {
        var $th1 = $('input[name="value_1"]');
        var $th2 = $('input[name="value_2"]');
        var $th3 = $('input[name="value_3"]');

        $th1.val( $th1.val().replace(/[^a-zA-Z0-9]/g, function(){ return ''; }) );
        $th2.val( $th2.val().replace(/[^a-zA-Z0-9]/g, function(){ return ''; }) );
        $th3.val( $th3.val().replace(/[^a-zA-Z0-9]/g, function(){ return ''; }) );
    });
});

and working fiddle:https://jsfiddle.net/04d5gkxd/2/

So in other words, group of fields: 2nd and 3rd must check the current value of 1st input, and base on that give the user possibility of picking proper value from 2nd and 3rd. Any ideas?


Solution

  • As @Alnitak suggested in the comments, you would be better suited to make the values set by some slider controls. You could have one which is a range of 50 - 100, and a second which is 0 - 50 that governs both the final values. Something like this:

    <div id="sliderA" class="slider"></div>
    <div id="sliderB" class="slider"></div>
    
    <input type="hidden" name="value_1" id="value_1" value="50" />
    <input type="hidden" name="value_2" id="value_2" value="0" />
    <input type="hidden" name="value_3" id="value_3" value="0" />
    
    $('#sliderA').slider({
        min: 50,
        max: 100,
        change: function(e, ui) {
            $('#value_1').val(ui.value);
        }
    });
    $('#sliderB').slider({
        min: 0,
        max: 50,
        change: function(e, ui) {
            $('#value_2').val(ui.value);
            $('#value_3').val(50 - ui.value);
        }
    });
    

    Working example