Skip to content

Instantly share code, notes, and snippets.

@uptonic
Last active January 4, 2017 19:45
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 uptonic/6b93c1d506e83244233a454c5023120b to your computer and use it in GitHub Desktop.
Save uptonic/6b93c1d506e83244233a454c5023120b to your computer and use it in GitHub Desktop.
Fix: Removes placeholder text when programmatically setting input.value in Safari
<!DOCTYPE html>
<html>
<head>
<title>Input Placeholder Test</title>
</head>
<body>
<script type="text/javascript">
// Proposed fix toggles readOnly state of generated input
// Ensures placeholder is properly removed after setting input.value
(function() {
var prototype = HTMLInputElement.prototype;
var descriptor = Object.getOwnPropertyDescriptor(prototype, "value");
if (descriptor) {
Object.defineProperty(prototype, "value", Object.assign({}, descriptor, {
set: function() {
var readOnly = this.readOnly
this.readOnly = !readOnly
var result = descriptor.set.apply(this, arguments)
this.readOnly = readOnly
return result
}
}));
}
})();
// Test case:
// 1) Generate a new <input>
// 2) Give <input> a placeholder attribute
// 3) Append to <body>
// 4) Set the value of the <input>
var input = document.createElement("input");
input.type = "text";
input.placeholder = "Due date";
document.body.appendChild(input);
setTimeout(function(){
input.value = "January 4, 2017";
}, 1000);
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment