How to use jQuery slider in MVC application

In this post, I will show how to use jQuery slider widget in MVC application. For example the following view shows that in my simulator I am trying to control value of number of rounds using slider as well as text box.

jquery slider

Add slider element to view

<div class="form-group">
<label for="Number" class="col-sm-3 control-label">Number of rounds</label>
<div class="col-sm-4">
        @Html.TextBoxFor(m => m.NumberOfRounds, 
        new { id = "numberofroundstext", @class = "form-control input-mini" })
<br />
<div id='roundcountslider'>
        </div>
    </div>
</div>

I have attached text box to model for my view. A new div has been added that will be placeholder for slider elements.

Glue form input to slider

Since slider element is not a form input element, you will need to glue that slider element with input element. This input element can be anything that will get posted to server when form is submitted. In my example, I have text box as that input element. If you do not have text box or some other visible element, you can always add hidden input. I have added following code to bottom of my partial view that implements the form.

 @section Scripts{
    @Scripts.Render("~/bundles/jqueryui")
        <script type="text/javascript">
            $(document).ready(function() {
                var roundslider = $("#roundcountslider").slider({
                    min: 1,
                    max: 50,
                    range: "min",
                    value: @Model.NumberOfRounds,
                    slide: function (event, ui) {
                        $("#numberofroundstext").val(ui.value);
                    }
                });
                $("#numberofroundstext").change(function () {
                    var rounds = new Number(this.value);
                    roundslider.slider("value", rounds);
                });
            }
            );
    </script>
}

The code provides two way glue between slider and text box. When slider is used to change the value, text box value is updated. When user enters a value directly in the text box, slider's value and position is changed.

This is pretty much all that you will need to use jQuery slider in your MVC view.

comments powered by Disqus

Search

Social

Weather

20.5 °C / 68.9 °F

weather conditions Clouds

Monthly Posts

Blog Tags