<button value="tab1View" class="tabButton current" id="tab1Tab">Tab 1</button>
<button value="tab2View" class="tabButton" id="tab2Tab">Tab 2</button>
<hr>
<div class="tabDiv" id="tab1View">This is tab 1
<br />There is a form on this tab. This form must be validated and submitted successfully before switching to tab 2.</div>
<div class="hidden tabDiv" id="tab2View">This is tab 2
<br/>The contents of this tab depend on the form in tab 1 having been successfully ssubmitted to the server.</div>
$(document).ready(function () {
$('.tabButton').click(changeTab);
//bind a "before show" function to tab 2
$('#tab2Tab').bind('beforeShow', tab2BeforeShow);
});
function changeTab() {
var jqButton = $(this);
jqButton.data('show', true); //start by assuming we will show the tab.
if (jqButton.hasClass("current")) //don't do anything if switching to the current tab
return;
//run the "before show" function, if any.
jqButton.trigger('beforeShow');
var showTab = jqButton.data('show'); //see if the show flag has been set to false
if (showTab === false) //if no before show function, then showTab is null, not false
return; //if false, then don't show the tab.
$(".tabDiv").hide();
//run any "after hide" scripts bound to the current tab
$('.tabButton.current').trigger('afterHide');
var requestedDiv = jqButton.val(); //the "value" of the tab button is the ID of the tab content div
$("#" + requestedDiv).show(); //may show nothing, if no div exists for the current tab.
$(".tabButton").removeClass("current"); //remove the current class from all tab buttons, so it will only be applied to the new current tab button.
jqButton.addClass("current");
}
function tab2BeforeShow() {
// run some AJAX function here. In my case, this is a ajaxForm object submit.
// $('#SomeajaxFormObject').submit();
var result;
$.ajax({
url: '/echo/json',
type: 'POST',
async: false,
success: function (response) {
alert(response);
if (response.success) result = true; // set the result variable declared in outer function
else result = false;
},
error: function () {
result = false; // bad response - dont show new tab
}
});
alert(result);
if (result === false) {
alert("Not showing tab due to response from ajax function");
$(this).data('show', false);
}
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.