views:

43

answers:

3

I need to dynamically alter a variable with the "name" attribute from a link - code below...

       <input type="text" class="datepicker" id="dp1">

       <a href="javascript:;" class="tab" name="1,2">test button</a>

and

$(document).ready(function(){

    var pickable = { dp1: [4,5,6] };

    $(".tab").click(function () { 
        var test = $(this).attr("name").split(",");
        pickable = { dp1:  test  };
    });

    $(".datepicker").each(function() {
        $(this).datepicker({
            beforeShowDay: function(date){ 
                var day = date.getDay(), days = pickable[this.id];
                return [$.inArray(day, days) > -1, ""];
            },
        });
    });

});​

Any ideas why this doesn't work??

+1  A: 

If you mean that the function passed to click is not being executed, check whether that code is being interpreted before the html.

Try wrapping the code in the ready function:

$(function () {
    var pickable = { dp1: [4, 5, 6] };
    $(".tab").click(function () { 
        var test = [ $(this).attr("name") ];
        pickable = { dp1:  test  };
    });
});

If the problem is that you want the string value of name, "1, 2", to be an array, you need to change your code a bit:

var pickable = { dp1: [4, 5, 6] };

$(".tab").click(function () { 
    var test = $(this).attr("name").split(",");
    pickable = { dp1:  test  };
});

Now, the value "1, 2" is being split by the , token and seperated into an array of values: ["1", "2"]

Andreas Grech
I have already done that, just didn't include it in the code i posted. sorry
Tom
I see what you're saying but it still doesn't work... here's a link to the code put in context, perhaps that'll work... http://jsfiddle.net/BhzE5/2/
Tom
A: 

If you intend to have var pickable available anywhere in your code, you might want to use, jquery data. You can try something like this:

    $(document).data('pickable', { dp1: [4, 5, 6] } );
    $(".tab").click(function () { 
        var test = $(this).attr("name").split(',');
        $(document).data('pickable', { dp1:  test  });
    });
erickb
Your example will create an array within an array: `[["1", "2"]]`
Andreas Grech
yes, I removed the surrounding []. Thanks
erickb
+1  A: 

Hi Tom

You can try something like this

$(document).ready(function(){

var pickable = ["2","3","4","5"];

function closedDays(date){
    var sDate = date.getDay().toString();
    if ($.inArray(sDate, pickable) == -1) return [false,"",""];
    else return [true, ""];
}

$(".tab").click(function () { 
   pickable =  $(this).attr("name").split(",");
     closedDays;
});

$(".datepicker").each(function() {
    $(this).datepicker({
        beforeShowDay:  closedDays
    });
});
});​

You can try it here http://jsfiddle.net/ZKW3b/2/

Jamie Taylor