Skip to content

Instantly share code, notes, and snippets.

@bulnak
Last active October 12, 2015 20:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bulnak/4085523 to your computer and use it in GitHub Desktop.
Save bulnak/4085523 to your computer and use it in GitHub Desktop.
support placeholder tag for unsupporting browser with jQuery val function overriding
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(); 호출 필요
@bulnak
Copy link
Author

bulnak commented Nov 16, 2012

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment