Development

Updating an input value from a jQuery slider

Live update an input value when sliding a jQuery Ui slider and set the slider value when the input is interacted with.

The CodePen example:

For this you need jQuery and jQuery UI, add in Bootstrap and a jQuery UI theme to give it a decent appearance.

The slider HTML elements:

<div class="custom-progress progress-up" style="width: 100%">
    <div id="rating_slider" class="ui-slider ui-corner-all ui-slider-horizontal ui-widget ui-widget-content">
    </div>
</div>

The input:

<label for="rating_input">Rating</label>
<input type="number" class="form-control" id="rating_input" value="50" min="0" max="100">

Initialize the slider with a minimum value of 0, a maximum value of 100 and a start value of 50. Add two events which call a function on slide and change states

$("#rating_slider").slider({
    min: 0, max: 100, value: 50,
    slide: function (event, ui) {//When sliding the toggle
        updateInputFromSlider("#rating_input", $(this).slider("value"));
    },
    change: function (event, ui) {//After releasing the toggle
        updateInputFromSlider("#rating_input", $(this).slider("value"));
    }
});

updateInputFromSlider function will set the input value to that of the slider

function updateInputFromSlider(input_id, value) {
    $(input_id).val(value);
}

Finally, when interacting with the input manually, update the slider value and position:

$(document).ready(function () {
    $("#rating_input").change(function () {
        $("#rating_slider").slider("value", $(this).val());
        $("#rating_slider").prop("value", $(this).val());
    });
});

 

 

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago