Search code examples
javascriptjqueryjquery-uijquery-ui-slider

jQuery UI range slider with letters


I have a jQuery UI Range slider like below working fine (pretty much a copy and paste from the jQuery API examples:

//Price range slider
$(function() {
    $( "#slider-range-price" ).slider({
        range: true,
        min: 300,
        max: 18499,
        values: [300,18499],
        slide: function( event, ui ) {
            $( "#amount-price" ).val( "£" + ui.values[ 0 ] + " - £" + ui.values[ 1 ] );
        }
    });
    $( "#amount-price" ).val( "£" + $( "#slider-range-price" ).slider( "values", 0 ) +
    " - £" + $( "#slider-range-price" ).slider( "values", 1 ) );
});

However now i need a second one, but this time i need it to handles letters instead of integers. As such i need the min: 'A' and the max :'Z', so that the range is 2 letters of the alphabet. But i have been unable to find anything other than integers or floats for sliders. Any help appreciated - bearing in mind i have done a lot of web-dev, but am pretty new to jQuery.


Solution

  • You can use min and max values which equate to the ASCII keycodes for A and Z respectively, then use String.fromCharCode() in the slide event to display them. Try this:

    $("#slider").slider({
      min: 65,
      max: 90,
      slide: function(event, ui) {
        $('#display').text(String.fromCharCode(ui.value));
      }
    });
    body {
      margin: 20px;
    }
    
    #display {
      margin: 20px 0 0;
      text-align: center;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/black-tie/jquery-ui.css" />
    <div id="slider"></div>
    <div id="display"></div>

    Alternatively, if you need the values sent to the server to be between 1 and 26, you can amend the ASCII code within the slide func:

    $("#slider").slider({
        min: 1,
        max: 26,
        slide: function( event, ui ) {
            $('#display').text(String.fromCharCode(ui.value + 64));
        }
    });