javascriptjqueryhtmljquery-uiglobal-object

How to use a dynamic property value in a jQuery widget


I have a javascript that returns a value whenever I choose an option from a dropdown menu.

   $(document).ready(function() {
        function calculateVals() { 
            //dropdown menus      
             var valuestart = $("select[name='timestart']").val();
             var valuestop = $("select[name='timestop']").val();

             //create date format          
             var timeStart = new Date("01/01/2007 " + valuestart).getHours();
             var timeEnd = new Date("01/01/2007 " + valuestop).getHours();

             var hourDiff = timeEnd - timeStart;                         

             return hourDiff;  

        }
        $("select").change(calculateVals);
        calculateVals();
    });

The script above returns a number which I need to add to a jquery plugin below. I need to add it to the max option but I get the error calculateVal is not defined.

$(function(){
    $("#slider").slider({
        range: "min",
        value:  8,
        min: 1,
        max: calculateVals(), //my attempt
        step: 1,
        slide: function(event, ui) {
            $("#amount").text(ui.value);
        },
         stop: function(event, ui) {
            $("#notifications").val(ui.value);
        }
    });
    $("#notifications").val( $("#slider").slider("value") );
});

Solution

  • Move the function to the global scope:

    function calculateVals() {       
        //code here...
        return someResult;                                           
    }
    
    $(document).ready(function() {
            $("select").change(calculateVals);
        calculateVals();
    });
    

    And even better, learn what does DOM ready means, as you misuse it.

    Update:

    You can later on change the slider max with:

    $( "#slider").slider("option", "max", calculateVals());