Posted By

talbs on 04/28/09


Tagged

form javascript plugin forms jquery label field useful accessible semantic overlay


Versions (?)

Who likes this?

4 people have marked this snippet as a favorite

benrudolph
Flocke
talbs
keith


[jQuery] inputLabel Plugin


 / Published in: jQuery
 

URL: http://www.dwightjack.com/diary/2008/12/24/semantic-in-field-input-label-with-jquery/

  1. /**
  2.  * jQuery Initial input value replacer
  3.  *
  4.  * Sets input value attribute to a starting value
  5.  * @author Marco "DWJ" Solazzi - [email protected]
  6.  * @license Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
  7.  * @copyright Copyright (c) 2008 Marco Solazzi
  8.  * @version 0.1
  9.  * @requires jQuery 1.2.x
  10.  */
  11. (function (jQuery) {
  12. /**
  13. * Setting input initialization
  14. *
  15. * @param {String|Object|Bool} text Initial value of the field. Can be either a string, a jQuery reference (example: $("#element")), or boolean false (default) to search for related label
  16. * @param {Object} [opts] An object containing options:
  17. * color (initial text color, default : "#666"),
  18. * e (event which triggers initial text clearing, default: "focus"),
  19. * force (execute this script even if input value is not empty, default: false)
  20. * keep (if value of field is empty on blur, re-apply initial text, default: true)
  21. */
  22. jQuery.fn.inputLabel = function(text,opts) {
  23. o = jQuery.extend({ color: "#666", e:"focus", force : false, keep : true}, opts || {});
  24. var clearInput = function (e) {
  25. var target = jQuery(e.target);
  26. var value = jQuery.trim(target.val());
  27. if (e.type == e.data.obj.e && value == e.data.obj.innerText) {
  28. jQuery(target).css("color", "").val("");
  29. if (!e.data.obj.keep) {
  30. jQuery(target).unbind(e.data.obj.e+" blur",clearInput);
  31. }
  32. } else if (e.type == "blur" && value == "" && e.data.obj.keep) {
  33. jQuery(this).css("color", e.data.obj.color).val(e.data.obj.innerText);
  34. }
  35. };
  36. return this.each(function () {
  37. o.innerText = (text || false);
  38. if (!o.innerText) {
  39. var id = jQuery(this).attr("id");
  40. o.innerText = jQuery(this).parents("form").find("label[for=" + id + "]").hide().text();
  41. }
  42. else
  43. if (typeof o.innerText != "string") {
  44. o.innerText = jQuery(o.innerText).text();
  45. }
  46. o.innerText = jQuery.trim(o.innerText);
  47. if (o.force || jQuery(this).val() == "") {
  48. jQuery(this).css("color", o.color).val(o.innerText);
  49. }
  50. jQuery(this).bind(o.e+" blur",{obj:o},clearInput);
  51.  
  52. });
  53. };
  54. })(jQuery);

Report this snippet  

You need to login to post a comment.