Search code examples
spinnersemantic-uinumericupdown

Semantic UI Numeric Up Down control


Is there any Semantic UI Numeric Up Down control with minimum, maximum and step count options ?


Solution

  • Not found such control so I made this code:

    HTML

    <div class="ui right labeled input">
        <input type="text" id="txtNum" value="5">
        <div class="ui mini vertical buttons">
            <button class="ui icon button" command="Up"> <i class="up chevron icon"></i>
    
            </button>
            <button class="ui icon button" command="Down"> <i class="down chevron icon"></i>
    
            </button>
        </div>
    </div>
    

    JS

    // Constants
    var KEY_UP = 38,
        KEY_DOWN = 40;
    
    // Variables
    var min = 0,
        max = 30,
        step = 1;
    
    $('.ui.icon.button').click(function () {
        var command = $(this).attr('command');
        HandleUpDown(command);
    });
    
    $('#txtNum').keypress(function (e) {
        var code = e.keyCode;
        if (code != KEY_UP && code != KEY_DOWN) return;
        var command = code == KEY_UP ? 'Up' : code == KEY_DOWN ? 'Down' : '';
        HandleUpDown(command);
    });
    
    function HandleUpDown(command) {
        var val = $('#txtNum').val().trim();
        var num = val !== '' ? parseInt(val) : 0;
    
        switch (command) {
            case 'Up':
                if (num < max) num += step;
                break;
            case 'Down':
                if (num > min) num -= step;
                break;
        }
    
        $('#txtNum').val(num);
    }
    

    Here is the DEMO.