Search code examples
jquery-uijquery-ui-slider

How to use jQuery UI slider in a function and pass different parameters for selectors?


I am a jQuery newbie. I've been trying to get the UI slider to work but haven't had any luck so far. What I want to do is be able to pass parameters to a function so that the parameter can be used as selectors in the slider. One of the parameters is the slider div's id and the other is the id of the input text box that goes along with it. Oh and the UI slider is a basic step slider as shown in the demos.

Here is the part of the HTML and JS files that concern this:

HTML PART:

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="content/jquery-ui/development-bundle/themes/smoothness/jquery.ui.all.css">
    <script type="text/javascript" src="content/jquery-ui/development-bundle/jquery-1.7.2.js"></script>
    <script type="text/javascript" src="content/jquery-ui/development-bundle/ui/jquery.ui.core.js"></script>
    <script type="text/javascript" src="content/jquery-ui/development-bundle/ui/jquery.ui.widget.js"></script>
    <script type="text/javascript" src="content/jquery-ui/development-bundle/ui/jquery.ui.mouse.js"></script>
    <script type="text/javascript" src="content/jquery-ui/development-bundle/ui/jquery.ui.slider.js"></script>
    <script type="text/javascript" src="journal.js"></script>
</head>
<body>
    <section id="journalEntry">
                <div id="base">
                    <label for="intensity">How intense was it?</label>  <input type="text" id="intensity" /><div id="intensityGuage"></div> 
                </div>
        </section>
</body>
</html>

jQuery Part:

$(document).ready(function(){
        guageBar(intensityGuage,intensity);
});

function guageBar(guageId,inputId){
        $( "[id='"+guageId+"']" ).slider({
            value:1,
            min: 1,
            max: 10,
            step: 1,
            slide: function( event, ui ) {
                $( "id[='"+inputId+"']" ).val( ui.value );
            }
        });
        $( "id=['"+inputId+"']" ).val( $( "id=['"+guageId+"']" ).slider( "value" ) );
}

Thanks in advance for your help :)


Solution

  • Try this:

    $(document).ready(function() {
        guageBar('intensityGuage', 'intensity');
    });
    function guageBar(guageId, inputId) {
        $("#" + guageId).slider({
            value: 1,
            min: 1,
            max: 10,
            step: 1,
            slide: function(event, ui) {
                $("#" + inputId).val(ui.value);
            }
        });
        $("#" + inputId).val($("#" + guageId).slider("value"));
    }​
    

    jsFiddle example

    You were passing variables instead of strings to your function, and you were also not referencing the IDs properly.