Highlight Twitter Bootstrap Error in Forms with Tabs

Craig Blanchette on Google+ on April 11th 2013

If you've used Twitter Bootstrap to create forms within tabs, then you might have come across a problem if you're using the "required" attribute in your form elements. If you do, you'll notice that (I use Chrome) you may find errors in the console stating that the element is not focus-able. There is a pretty easy solution to fix this: If there is an error in one of the form elements, we'll search to find the closest element with the class ".tab-pane". Once we've done that, we can get the element's id attribute, and then find the link that corresponds to the pane, and call the Bootstrap .tab() function on it. Here's what that looks like:

  1. $(function(){
  2. $('.tab-pane input, .tab-pane textarea').on('invalid', function(){
  4. // Find the tab-pane that this element is inside, and get the id
  5. var $closest = $(this).closest('.tab-pane');
  6. var id = $closest.attr('id');
  8. // Find the link that corresponds to the pane and have it show
  9. $('.nav a[href="#' + id + '"]').tab('show');
  11. });
  12. });