Reputation: 567
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:
select
event is apparently getting overridden by the click event, so text
is not setI'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.
Upvotes: 1
Views: 1970
Reputation: 567
I discovered the problem: I am indeed a n00b.
I was setting the text
variable 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:
if ( $('#tab_container').is(':visible') ) {
// now we can safely set this variable...
var activePanel = '.ui-tabs-panel:visible ';
// ...and this will always have a value
var text = $(activePanel + 'someElement').val();
}
Upvotes: 1