views:

564

answers:

1

How do you bind a function for each index of the jquery UI tabs?

For example, I am creating a 3 part slide sign up, step 1 is a form and has validation, I want to place the code for that inside the load of step1, while also adding classes to the tabs to disable #2 and #3 when on 1, disable #1 and # 3 when on #2

A: 

There is no need to bind a function to the tabs, it's built into the plugin:

From the plugin page:

$('#tabs').tabs({
   select: function(event, ui) { ... }
});

Inside the function, you can determine the current tab you are in and do what you need to do from there:

  • Get the current tab index

    currentTabIndex = $('#tabs').tabs('option', 'selected')
    
  • Get the current tab content ID (from href) - there might be an easier way, but I haven't found it yet.

    currentTabContent = $( $('.ui-tabs-selected').find('a').attr('href') );
    

but from seeing the other questions you posted about this tab/form system you are trying to use, I threw together a demo here.

HTML

<div id="tabs">
 <ul class="nav"> <!-- this part is used to create the tabs for each div using jquery -->
  <li class="ui-tabs-selected"><a href="#part-1"><span>One</span></a></li>
  <li><a href="#part-2"><span>Two</span></a></li>
  <li><a href="#part-3"><span>Three</span></a></li>
 </ul>

 <div id="part-1">
  <form name="myForm" method="post" action="" id="myForm">
   <div class="error"></div>
    Part 1
    <br /><input type="checkbox" /> #1 Check me!
    <br />
    <br /><input id="submitForm" type="button" disabled="disabled" value="next >>" />
  </form>
 </div>

 <div id="part-2">
  <div class="error"></div>
   Part 2
   <br />Search <input type="text" />
   <br />
   <br /><input id="donePart2" type="button" value="next >>" />
 </div>

 <div id="part-3">
  <div class="error"></div>
   Part 3:
   <br />Some other info here
 </div>
</div>

Script

$(document).ready(function(){
 // enable Next button when form validates
 $('#myForm').change(function(){
  if (validate()) {
   $('#submitForm').attr('disabled','')
  } else {
   $('#submitForm').attr('disabled','disabled')
  }
 })
 // enable form next button
 $('#submitForm').click(function(){
    // enable the disabled tab before you can switch to it, switch, then disable the others.
  if (validate()) nxtTab(1,2);
 })
 // enable part2 next button
 $('#donePart2').click(function(){
    var okForNext = true; // do whatever checks, return true 
  if (okForNext)  nxtTab(2,1);
 })
 // Enable tabs
 $('#tabs').tabs({ disabled: [1,2], 'selected' : 0 });
})
function validate(){
 if ($('#myForm').find(':checkbox').is(':checked')) return true;
 return false;
}
function nxtTab(n,o){
 // n = next tab, o = other disabled tab (this only works for 3 total tabs)
 $('#tabs').data('disabled.tabs',[]).tabs( 'select',n ).data('disabled.tabs',[0,o]);
}
fudgey