views:

979

answers:

2

I have a jQuery accordion in a page in ASP:Net MVC application in which I want to set the active accordion at runtime.

IMy code is as follows:

<script type="text/javascript">
    $(document).ready(function() {
        var accordionindex = $("#UIPViewModel_ActiveAccordion").val();
        alert("Setting active index to " + accordionindex);
        $("#accordion").accordion('activate', accordionindex );
    });
</script>

You will see the last line sets the active accordion. When I use this code it always acts like I have used active : false and ALL of the accordions are closed even though the alert displays the correct runtime value.

I have also tried simply using the following which is the same:

$("#accordion").accordion('activate', $("#UIPViewModel_ActiveAccordion").val());

When I change the last line to :

$("#accordion").accordion('activate', 2 ); (i.e. hard-coded). It always works correctly!

Can anyone see what´s wrong?

+1  A: 

Yes, the variable being returned by val() is a string and accordion is expecting a number. Try:

    var accordionindex = $("#UIPViewModel_ActiveAccordion").val();
    accordionindex = parseInt(accordionindex, 10);  // convert a string to a number
    alert("Setting active index to " + accordionindex);
    $("#accordion").accordion('activate', accordionindex );
Ken Browning
This was the issue. Also, as I am GETting the same page again, and using activate caused a less than satisfactory slide to the selected accordion. I got a hint from another post here about 'destroy' and then recreate athe accordion with the active accordion selected and the page refreshes without any accordion UI effect as required. I used: $("#accordion").accordion('destroy'); $("#accordion").accordion({ active: parseInt(accordionindex) });
Redeemed1
I've been trying to find a solution to this for HOURS! Something as simple as string vs. integer. Wow.
Paul
+1  A: 

Just to extend Ken's solution:

<script type="text/javascript"> 
$(function () {
    var accordionindex = Number($("#UIPViewModel_ActiveAccordion").val());
    alert("Setting active index to " + accordionindex);
    $("#accordion").accordion('activate', accordionindex );
});
</script>

You really only need to use the parseInt if there is some chance that the val() will ever be something other than normal digits (like if it had "index 4" for the value). And you can cast it as a digit while you set the var.

Anthony
actually the value is coming form a Hidden field populated with an int value. Appears that the hidden field value must be returned as a string
Redeemed1
values are always strings when they come out of the DOM. Even if you cast them as integers or floats and then inject them into the DOM from js. I learned that the hard way.
Anthony