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??
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 );
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With