문제

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") );
});
도움이 되었습니까?

해결책

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.

  • You should have only one ready handler.
  • Only code relevant to DOM elements should be there.

Update:

You can later on change the slider max with:

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

다른 팁

Try defining the function out side the ready block:

function calculateVals() { 

             //code here...

             return someResult;                                          
}



$(document).ready(function() {
    $("select").change(calculateVals);
    calculateVals();
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top