jqueryerror-handlingjquery-ui-tabs

Making a jQuery Tab Selected based on errors present


I am working to get a tab in my web application to show selected IF there is an error within it, because I have a form that spans the two tabs. For now if there is an error the user can not see the error message inside tabs-2 and they don't know what to fix. I have the following code:

HTML:

<div id="tabs">
  <ul>
    <li><a id="Tab-1" href="#tabs-1">Tabs 1</a></li>
    <li><a id="Tab-2" href="#tabs-2" ">Tabs 2</a></li>
  </ul>
  <div style="display:block;" id="tabs-1" class="tab-content" name="content">
    <span>Content here</span>
  </div>
  <div style="display:block;" id="tabs-2" class="tab-content" name="content">
    <span id="ETError" class="error-template"></span>
    <span class="error-message">Must enter at least one more</span>
  </div>
</div>

JS:

<script>
  var $j = jQuery.noConflict();

  $j(function() {
    $j( '#tabs' ).tabs();
    $j('#tabs > div').each(function(i) {
      if($j(this).find('#ETError.error-message').length < 0)
        $j('#tabs').tabs('select', i);
    });
  });
</script>

Solution

  • From what I understand, you want to set tab to active if there's an error message is present. Check this if that's what you wanted or let me know if there's something else I'm missing here.

    var $j = jQuery.noConflict(); 
    var $tabs = $j( '#tabs' ).tabs();       
    
    $j("button").click(function(){
        var $errorSpan = $j("span").filter(function(index){        
            if($j(this).hasClass("error-message"))
            return $j(this);
        });
    
        var errorTabIndex = $j(".tab-content").index($errorSpan.closest(".tab-content"));
    
        console.log(errorTabIndex);
    
        // for jQuery < 1.10
        $tabs.tabs({
            selected: errorTabIndex
        });
    
        //for jQuery >= 1.10
        $tabs.tabs( "option", "active", errorTabIndex);
    
    });
    

    I've added handler to check for error-div on button tap. You might want to set it to form submit or something.

    DEMO HERE

    Update

    What is done is, a filter is applied on span.error-message. If found any it returns that span. Then we can find the tab which is having that error message and set it active.