user3066721
user3066721

Reputation:

jQuery UI tabs, validate before switching tabs

I'm using jQuery UI tabs on a private project.

my tabs are identified like this:

  <ul>
    <li><a href="#tab1">tab1</a></li>
    <li><a href="#tab2">tab2</a></li>
    <li><a href="#tab3">tab3</a></li>
    ....
  </ul>

All of this is working fine.

However in the content of each tab i have some forms. i need that when i click on #tab2, while #tab1 is active, do some validations in the form in #tab1, and if everything is ok show that tab.

I have this listener for the tabs

    $('a[href$="#tab1"]').click(function(){
        return false;
    });

Checked around SO and found answers telling to return false, (that didn't worked) others pointed to the official docs, but i could not apply a working solution.

How can i do it?

Edit

Here is the fiddle

Fiddle

Upvotes: 1

Views: 2663

Answers (4)

Irvin Dominin
Irvin Dominin

Reputation: 30993

You can use beforeActivate event and check if all inputs in the old panel are filled.

Code:

$("#tabs").tabs({
    beforeActivate: function (event, ui) {
        var $emptyFields = $("input",ui.oldPanel).filter(function () {
            return $.trim(this.value) === "";
        });
        if ($emptyFields.length) return false
    }
})

Demo: http://jsfiddle.net/IrvinDominin/5ypo0xgo/

Upvotes: 0

Alexander Ceballos
Alexander Ceballos

Reputation: 760

you can do this:

 $('#mydiv').tabs({
        activate: function(event, ui) {
            var sel = ui.newPanel.attr('id');
            if (sel == 'mydiv1' )
            {
                if(!validate()){
                    $(this).tabs({
                        active: 0
                    });
                }
            }

            if (sel == 'mydiv2' )
            {
                if(!validate()){
                    $(this).tabs({
                        active: 1
                    });

                }
            }
        }});

Upvotes: 0

DJ22T
DJ22T

Reputation: 1640

From the Official documentation beforeActivate

This will trigger immediately before a tab is activated, allowing you to do your validations and allow the tab to be shown.

$( "#tabs" ).tabs({
  beforeActivate: function( event, ui ) {
    var clicked_id = ui.newPanel.attr('id');
    if (clicked_id == 'tab2' )
    {
       // Do your validations
        return false;
    }
    .... 
  }
});

Upvotes: 2

Marcel
Marcel

Reputation: 1191

This will only go to the next tab it all the inputs in the current the are not empty:

$("a[href*='tab']").click(function(){
    if($("input[value='']").length > 0){
        return false;
    }
}

Upvotes: 0

Related Questions