Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Accordion setting active

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??

like image 434
Redeemed1 Avatar asked Sep 10 '09 23:09

Redeemed1


2 Answers

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 );
like image 135
Ken Browning Avatar answered Oct 27 '22 20:10

Ken Browning


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.

like image 25
Anthony Avatar answered Oct 27 '22 21:10

Anthony