Reputation: 2084
I am using bootstrap tabs, and I use the shown
event to detect the tab change, in a scenario I want to cancel this shown even so I used the preventDefault()
function as following :
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
var target = $(e.target).attr("href") // activated tab
if(target === '#mise-en-page' || target === '#widgets'){
if($('.page-name-input').length > 0){
var nonEmpty = $('.page-name-input').filter(function(){
return this.value != '';
});
if(nonEmpty.length==0){
e.preventDefault();
console.log('Error !!');
}else{
console.log('OK');
}
}else{
console.log('OK');
}
};
});
In this case the preventDefault()
function didn't work and I still can navigate between tabs even if I had the 'Error !!'
message printed on my console.
How can I solve this ?
This is a jsfiddle where the preventDefault()
doesn't work with the shown event.
http://jsfiddle.net/xFW8t/2426/
Upvotes: 4
Views: 5439
Reputation: 362360
It's happening because the fiddle doesn't properly include bootstrap.js
When the js is included the e.preventDefault
works fine..
http://www.codeply.com/go/FiyO9EGNC0 (css, js & jquery all included w/Codeply)
The tabs are still working w/o the js because of the data-attributes, but the events won't work w/o bootstrap.js
Upvotes: 4
Reputation: 286
shown.bs.tab is fired once the tab has been shown. In order to avoid the default behaviour you should listen to the previous step, try like this:
$('a[data-toggle="tab"]').on('show.bs.tab', function (e) {
//your stuff
});
Although I'm not sure if you will be able to prevent the default behaviour for a custom library. PreventDefault is meant to be use for default behaviours of the language not custom ones.
Upvotes: 4