jQuery UI Slider with Hidden Input

by john_s

HTML

<form id="testForm">
    <div id="slider" data-name="price" data-id="priceId" data-value="$25"></div>
</form>
<br />
<div id="output"></div>

JavaScript

$(function() {
    // Instruments each element with a slider. For each element that is
    // instrumented, a hidden input element is generated and inserted into
    // the document. The hidden input is automatically updated with the
    // value of the slider.
    // The following "data-" attributes are supported on the elements:
    //   data-name: (Required) This is used for the "name" attribute of the
    //              hidden input element.
    //   data-id: (Optional) This is used for the "id" attribute of the
    //            hidden input element.
    //   data-value: (Optional) This is used for the initial value of the
    //               hidden input element. The initial value of the slider
    //               will be set to match. If this is not specified, the
    //               initial value will be the first value in the array.
    // Parameters:
    //   values - an array of strings
    //   options - optional options object. These are the options supported
    //             by a jQuery UI slider, but you really shouldn't include
    //             "min", "max", "range", or "values".
    jQuery.fn.inputSlider = function(values, options) {
        options = $.extend({min: 0, max: values.length - 1}, options);
        var changeCallback = options.change;
        return this.each(function() {
            var $element = $(this);
            var value = $element.data('value') || values[0];
            var $input = $('<input type="hidden" />').attr({
                name: $element.data('name'),
                value: value
            });
            var inputId = $element.data('id');
            if (inputId) {
                $input.attr('id', inputId);
            }
            $element.slider($.extend(options, {
                change: function(event, ui) {
                    $input.val(values[ui.value]);
                    if (changeCallback) {
                        changeCallback.call(this, event, ui);
                    }
               ...