2

I'm trying to create multiple jquery UI sliders using a single CSS class and HTML5 data-* values, but without success. I can get some values, but some simply doesn't work.

Here is the code: http://jsfiddle.net/Smartik/FTtAb/1/

As you can see, data-id and data-val works but I can't get values for data-min, data-max, data-step(which are the most important already). Try to uncomment these lines and see what's happen.

So, my question; is there a way to get these values using data-* or something else?

1
  • Your example is working for me : sliders works, callback too to update the slider value... What is not working for you? Commented Mar 17, 2013 at 10:06

2 Answers 2

2

The values you extract from your data- attributes are strings, not numbers. The min, max and step options of the jQuery UI slider widget only take numbers.

You can use parseInt() to convert these values to numbers:

var min   = parseInt(jQuery('#' + id).attr('data-min'), 10);
var max   = parseInt(jQuery('#' + id).attr('data-max'), 10);
var step  = parseInt(jQuery('#' + id).attr('data-step'), 10);

You will find an updated fiddle here.

(As an aside, consider caching the result of jQuery('#' + id) in a local variable for efficiency).

Sign up to request clarification or add additional context in comments.

Comments

1

Apart from parseInt you should also use the data function. Here is a modified fiddle:

http://jsfiddle.net/FTtAb/3/

jQuery('.sliderui').each(function() {
    var obj = jQuery(this);
    var sId   = "#" + obj.data('id');
    var val   = parseInt(obj.data('val'));
    var min   = parseInt(obj.data('min'));
    var max   = parseInt(obj.data('max'));
    var step  = parseInt(obj.data('step'));


    obj.slider({
        value: val,
        min: min,
        max: max,
        step: step,
        slide: function( event, ui ) {
            jQuery(sId).val( ui.value );
        }
    });
});

2 Comments

Using data() can make this more readable indeed. On the other hand, you should always specify the radix you want parseInt() to use, otherwise you can get strange results or even errors depending on the data- attribute value (e.g. 042 will be parsed as 34 instead of 42).
Look so simple now. Thank you very much for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.