Posted By

davebowker on 10/17/08


Tagged

form clear input jquery label field restore


Versions (?)

JQuery ToggleVal


 / Published in: JavaScript
 

URL: http://jquery.kuzemchak.net/toggleval.php

Use by inserting the following in the head. $(document).ready(function() { $("input").toggleVal(); });

  1. /* -------------------------------------------------- *
  2.  * ToggleVal 2.0
  3.  * Updated: 9/15/08
  4.  * -------------------------------------------------- *
  5.  * Author: Aaron Kuzemchak
  6.  * URL: http://aaronkuzemchak.com/
  7.  * Copyright: 2008 Aaron Kuzemchak
  8.  * License: MIT License
  9. ** -------------------------------------------------- */
  10.  
  11. (function($) {
  12. $.fn.toggleVal = function(theOptions) {
  13. theOptions = $.extend({
  14. focusClass: "tv-focused", // class during focus
  15. changedClass: "tv-changed", // class after focus
  16. populateFrom: "default", // choose from: default, label, or alt
  17. removeLabels: false // remove labels associated with the fields
  18. }, theOptions);
  19.  
  20. return this.each(function() {
  21. // define our variables
  22. var defText = "";
  23.  
  24. // let's populate the text, if not default
  25. switch(theOptions.populateFrom) {
  26. case "alt":
  27. defText = $(this).attr("alt");
  28. $(this).val(defText);
  29. break
  30. case "label":
  31. defText = $("label[for='" + $(this).attr("id") + "']").text();
  32. $(this).val(defText);
  33. break
  34. default:
  35. defText = $(this).val();
  36. }
  37.  
  38. // let's give this field a special class, so we can identify it later
  39. $(this).addClass("toggleval");
  40.  
  41. // now that fields are populated, let's remove the labels if applicable
  42. if(theOptions.removeLabels == true) { $("label[for='" + $(this).attr("id") + "']").remove(); }
  43.  
  44. // on to the good stuff... the focus and blur actions
  45. $(this).focus(function() {
  46. if($(this).val() == defText) { $(this).val(""); }
  47.  
  48. // add the focusClass, remove changedClass
  49. $(this).addClass(theOptions.focusClass).removeClass(theOptions.changedClass);
  50. }).blur(function() {
  51. if($(this).val() == "") { $(this).val(defText); }
  52.  
  53. // remove focusClass, add changedClass if, well, different
  54. $(this).removeClass(theOptions.focusClass);
  55. if($(this).val() != defText) { $(this).addClass(theOptions.changedClass); }
  56. else { $(this).removeClass(theOptions.changedClass); }
  57. });
  58. });
  59. };
  60. })(jQuery);

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: davebowker on October 17, 2008

<script type="text/javascript"> $(document).ready(function() { $("input").toggleVal(); });
</script>

You need to login to post a comment.