How to change jQuery UI Slider value from textbox in ASP.NET

I had recently posted about how to use jQuery slider with ASP.NET which I had also used for my client. But my client came up with one more requirement which is user can either select value from slider or can enter in a textbox. Based on the value entered in textbox, slider value should also change accordingly. See below image.

In how to use jQuery slider with ASP.NET post, I had shown you how to use label control to display sliders value. This time, we are using a textbox. So we need to change the code as .text() function can't be used for textbox. we need to use .val() function for textbox.

$(document).ready(function(){
  $("#slider").slider(
  { 
     min:0,
     max:250,
     slide:function(event,ui){
        $("#txtVal").val(ui.value);
     }
  });
});

Now, we need to change the slider control value according to textbox. We need to use the change function of textbox to change the slider control value. See below code.

$("#txtVal").change(function(event) {
  var data = $("txtVal").val();
  $("#slider").slider("option", "value", data);
});

We have used the value option of slider to set the value of slider control. Just run your code and enter any value between 0-250. But we have not implemented any validation which is not correct from end-user perspective.
There are couple of ways to implement the validation.
1. You can use ASP.NET Range validator control.
2. Allow only numbers in textbox and validate it's value on keypress event.

I have also extended the change event for following functionalities.
   1. If value entered by user is less than minimum value then set it to the slider's min value.
   2. If value entered by user is greater than maximum value then set it to the slider's max value.
   3. If nothing is entered by user then set slider's value to it's minimum value.

$("#txtVal").change(function(event) {
  var data = $("txtVal").val();
  if (data.length > 0) 
  {
     if (parseInt(data) >= 0 && parseInt(data) <= 250) 
     {
         $("#slider").slider("option", "value", data);
     }
     else
     {
 if (parseInt(data) < 0) 
        {
   $("#txtVal").val("0");
          $("#slider").slider("option", "value", "0");
        }
        if (parseInt(data) > 250) 
        {
          $("#txtVal").val("250");
          $("#slider").slider("option", "value", "250");
        }
     }
  }
  else
  { 
    $("#slider").slider("option", "value", "0"); 
  }  
});

As clear from above jQuery code, I have used parseInt() function to parse the input in integer type and based on various conditions, slider's value is set.

See live Demo and Code

Feel free to contact me for any help related to jQuery. I will gladly help you.



Responsive Menu
Add more content here...