I’m having some trouble selecting a tab programmatically. My tabs are loading inside a Fancybox dialog window, which is launched on click of a link. Basically, I want to perform certain actions any time a tab is selected, and also select a specific tab when a link is clicked.
I am initializing jQuery UI Tabs with the select event like so:
$('#tabs').tabs({
select: function(event, ui) {
// edit: here is the issue
var activePanel = '.ui-tabs-panel:visible ';
// grab value of a form input
var text = $(activePanel + 'someElement').val();
// check its length
if ( text.length > 0 ) {
// do stuff
}
}
})
Later on in my JS file I have the following:
$(document).on('click', 'a.edit', function() {
if($category == 'book') {
// load the tab specific to the 'book' category
$('#tabs').tabs({ selected: 3 });
}
})
When I click the a.edit link for an item in the “book” category, my console throws this error:
Uncaught TypeError: Cannot read property 'length' of undefined
Then, instead of the tabs loading in the Fancybox, nothing happens. This error is not thrown when I click the link for items that are not in the book category. Thus, two things are painfully evident:
- I am a n00b
- My
selectevent is apparently getting overridden by the click event, sotextis not set
I’ve tried setting a default for text at the top of my JS file but that doesn’t work. My question, then, is:
What is the correct way to initialize UI Tabs with a select event, while also being able to programmatically select a tab with a click event?
Or, more concisely,
Why am I getting that damn error?
Edit: I amended my first code block above to include code that I discovered was relevant to my problem. See my answer below for a fuller explanation.
I discovered the problem: I am indeed a n00b.
I was setting the
textvariable based on whether or not the tab was visible. Because my tabs were hidden by default, there was never a visible panel from which to grab a value.I solved the problem by adding a simple check to see if the parent element was visible before assigning the variable: