support placeholder tag for unsupporting browser with jQuery val function overriding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function initPlaceholder() { | |
if (!("placeholder" in document.createElement("input"))) { // Browser 지원여부 체크 | |
var $input_placeholder = $("input[placeholder]"); | |
$input_placeholder.each(function () { | |
$(this).focus(function () { | |
if ($(this).val().trim() == "") { | |
$(this).css("color", "").val(""); | |
} | |
}).blur(function () { | |
if ($(this).val().trim() == "") { | |
$(this).css("color", "#a6a6a6").val($(this).attr("placeholder")); | |
} else { | |
$(this).css("color", ""); | |
} | |
}).blur(); | |
}); | |
// jQuery val function overriding for placeholder | |
(function ($) { | |
var org_val = $.fn.val; | |
$.fn.val = function (value) { | |
var placeholder = $(this).attr("placeholder"); | |
if (typeof value != "undefined") { // setter | |
if ((value == "" || value == placeholder) && $(this).is("input[placeholder]:not(:focus)")) { | |
$(this).css("color", "#a6a6a6"); | |
value = placeholder; | |
} else { | |
$(this).css("color", ""); | |
} | |
return org_val.call(this, value); | |
} | |
else { // getter | |
if( this[0].value == placeholder ) { | |
this[0].value = ""; | |
} | |
return org_val.call(this); | |
} | |
}; | |
})(jQuery); | |
} | |
} | |
// initPlaceholder(); 호출 필요 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
document 객체를 직접 건드리는 경우에는 한계가 있음.
$("#input1").val(""); // display well
document.getElementById('input1').value = ""; // placeholder text doesn't display
var text = $("#input1").val(); // returns ""
var text = document.getElementById('input1').value; // returns text of placeholder attribute