-3

i am using JavaScript to display an event calender. I want to show all the events dynamically. I have to fetch the values using ajax. The value is properly printed in the function but I want to use these value variables outside the function.

my function is:-

$(function () {
    $("#calendar").datepicker({
        dateFormat: 'mm/dd/yy',
        beforeShowDay: checkBadDates
    });

});

function calendarnew(apdate) {
    dt = "";
    var myData = apdate.split(",");
    alert(myData);
    dt = myData.join('","');
    dt.replace(/\s+/g, '');
    return dt;
}

var $myBadDates = new Array("10 May 2014", "21 May 2014", "12 May 2014");

function checkBadDates(mydate) {
    var $return = true;
    var $returnclass = "available";
    $checkdate = $.datepicker.formatDate('dd MM yy', mydate);
    for (var i = 0; i < $myBadDates.length; i++) {
        if ($myBadDates[i] == $checkdate) {
            $return = false;
            $returnclass = "unavailable";
        }
    }
    return [$return, $returnclass];
}

$(document).ready(function () {

    calendarnew();
});

</script>

in this function how i use " dt " variable outside the function in the " $myBadDates ". please, suggest me.

nettux
  • 5,270
  • 2
  • 23
  • 33
Ranjeet singh
  • 794
  • 1
  • 16
  • 38

2 Answers2

0

Just define your variables out of function:

var x = null;

function f() {
    x = 2
}

f();
console.log(x);
MostafaR
  • 3,547
  • 1
  • 17
  • 24
  • Hye, i am using it like:- var dt=""; function calendarnew(apdate) { var myData = apdate.split(","); alert(myData); dt=myData.join('","'); dt.replace(/\s+/g, ''); alert(dt); return dt; } calendarnew(); alert(dt); but it can't work – Ranjeet singh May 14 '14 at 09:56
  • Placing code with more than one line in a comment is not a good idea. But your commented code works as well, the only wrong thing is that you're calling `calendarnew();` without any argument, you should change it to `calendarnew('something');`. – MostafaR May 14 '14 at 16:09
0

You need to define and scope (with var) your variables outside the function eg:

var i = 0;
console.log(i);
function i_plus() {
    i++;
} 
i_plus();
console.log(i);

outputs to the console:

0
1

See here for more info on variable scopes in JavaScript:

What is the scope of variables in JavaScript?

Community
  • 1
  • 1
nettux
  • 5,270
  • 2
  • 23
  • 33