Search code examples
jqueryasp.net-mvcjquery-uirazorjquery-ui-slider

Show slider value for each slider in cshtml


I want to show a list of items, each with it's own slider in a Razor file.

So with limited knowledge I managed to show the sliders for all the items, but how can I show the slider value in the input text box? I.e. as the slider moves the value should be displayed.

foreach (var item in Items)
{
   @item.Description
   <input type="text" id="value@(item.UniqueID)">
   <div class="slider" id="slider@(item.UniqueID)"></div>
}

<script>
    $(function () {
        $(".slider").slider();
        ????
    });
</script>

Solution

  • First, check the API documentation: http://api.jqueryui.com/slider/

    This shows a number of events you can use - "as the slider moves" implies the slide event.

    Next, you need to link the slider and the input - you could do this using .prev, but then your html will be fixed, or you could dynamically subtract 'slider' and add 'value', but again, risks breaking in future - so the easiest option is to add the related input to the slider div (there are various ways to do this, the below is quite straightforward):

    <div class='slider' 
         id='slider@(item.UniqueID)' 
         data-inp='value(@item.UniqueID)'>
    </div>
    

    then add a handler for the slide event:

    $(function() {
        $(".slider").slider();
        $(".slider").on("slide", function(e, ui) {
            $("#" + $(this).data("inp")).val(ui.value);
        });
    });
    

    Here's a fiddle to show it working for a single input/slider: http://jsfiddle.net/76d4t8p3/