Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Validate on Tab change

I am working with jQuery Validate and Tabs plugins. I wish to validate a particular tab when the user attempts to move away from the tab to one of the other 2 tabs. Does anyone have experience with this particular method?

Currently, this is how I bind the Tabs plugin:

   $(function() {
      //Bind Link Tab Selection
      //------------------
      var $tabs = $("#tabs").tabs();
       $('#step1_button').click(function() {
          $tabs.tabs('select','2');
          return false;
       });
       $('#step2_button').click(function() {
          $tabs.tabs('select','3');
          return false;
       });
       //------------------
       //------------------

       //Bind Tabs
       //------------------
       $("#tabs").tabs({
          fx: {width:'toggle'}
       });
       //------------------
       //------------------
    });
like image 863
cbm3384 Avatar asked Sep 07 '11 15:09

cbm3384


1 Answers

You can run a function every time the tab is changed like so:

$("#tabs").tabs({
        select: function(event, ui) {
            // Do your validation here
        }        
});

You can have a look at the official documentation here. The event stuff is down at the bottom.

So you can do your validation inside that function for some controls in that tab. Also instead of selecting different tabs manually, you can get the index of the tab you're selecting inside the function also by using ui.index. Additionally, you could very easily prevent the user from changing to another tab if the current tabs content isn't valid by using event.preventDefault(). So altogether, something like...

$("#tabs").tabs({
        select: function(event, ui) {
            alert('validating tab ' + ui.index);

            var valid = false;

            // do your validating here...
            // determine validity

            // If the form isn't valid, prevent the tab from changing
            if(!valid)
            {
                // prevent further action
                event.preventDefault();
            }
            else
            {
                // valid so we'll allow user to change tab
                alert('valid');
            }
        }        
});

You can play about with the code here.

like image 142
David Spence Avatar answered Oct 02 '22 16:10

David Spence