jQuery Spellchecker - Multiple fields demo

This page demonstrates how to use the spellchecker on multiple form fields. You can also view the basic demo.

(function() {

  // This code will only work with Twitter Bootstrap

  var toggle = (function() {
  
    var fields = $('input:text,textarea');
    var spellchecker = null;

    function showPopover() {
      $('.popover').hide().find('.popover-content').each(function(){ 
        if ($(this).find('a').length) {
          $(this).parents('.popover').show();
          return false;
        }
      });
    }

    function create() {

      spellchecker = new $.SpellChecker(fields, {
        lang: 'en',
        parser: 'text',
        webservice: {
          path: '../webservices/php/SpellChecker.php',
          driver: 'pspell'
        },
        suggestBox: {
          position: 'below'
        },
        incorrectWords: {
          position: function(container) {
            this.after(container);
          }
        }
      });

      spellchecker.on('check.success', function() {
        alert('There are no incorrectly spelt words.');
      });

      spellchecker.on('check.fail', function() {

        fields.each(function() {
            
          var field = $(this);

          if (field.data('popover')) {
            return;
          }
          
          field.popover({
            trigger: 'manual',
            placement: 'bottom',
            title: '<i class="icon-info-sign"></i> Spelling errors'
          })
          .popover('show')
          .data('popover')
          .$tip
          .find('.popover-content')
          .append(field.next());
        });
       
        showPopover();
      });

      spellchecker.on('replace.word', function(incorrectWords) {
        showPopover();
      });

      spellchecker.check();
    }

    function destroy() {
      spellchecker.destroy();
      spellchecker = null;
      fields.popover('destroy');
    }

    function toggle() {
      (!spellchecker) ? create() : destroy();
    }
  
    return toggle;
  })();

  // Check the spelling
  $("#check-spelling").click(toggle);
})();