gh.forms.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. gh.provide('gh.forms');
  2. /**
  3. * Focuses the first element in the given form. If the form has been
  4. * submitted and has invalid elements, the first invalid element is
  5. * focused. Invisible elements and submit buttons will not be focused.
  6. *
  7. * @param formSelector A CSS selector for the form, e.g. '#LoginForm'.
  8. */
  9. gh.forms.autofocus = function(formSelector) {
  10. var form = $(formSelector);
  11. var invalidElements = form.find('.invalid:visible:not([type="hidden"]):not([type="submit"])');
  12. if (invalidElements.length == 0) {
  13. var allElements = form.find('input:visible:not([type="hidden"]):not([type="submit"]), textarea:visible, select:visible');
  14. if (allElements.length > 0) {
  15. $(allElements[0]).focus();
  16. }
  17. } else {
  18. $(invalidElements[0]).focus();
  19. }
  20. };
  21. /**
  22. * Prevents the given form from being submitted more than once.
  23. *
  24. * @param formSelector A CSS selector for the form, e.g. '#LoginForm'.
  25. */
  26. gh.forms.disableOnSubmit = function(formSelector) {
  27. var form = $(formSelector);
  28. form.submit(function(e) {
  29. if (form.data('submitted')) {
  30. e.preventDefault();
  31. } else {
  32. form.data('submitted', true);
  33. }
  34. });
  35. };