Question

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

My 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? Where i am making my mistake??

Was it helpful?

Solution

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 );

OTHER TIPS

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.

for newer versions, the way to activate (and deactivate) the panel has changed:

jQuery(".selector").accordion("option", {active: index});

Took me a while to figure out I wasn't crazy -- jQueryUI 1.8 supports the activate method. They got rid of it for 1.9 and above.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top