Last Updated: February 25, 2016
·
1.468K
· devers

Clear inputs that have default text

Sometimes the HTML5 placeholder attribute isn't ideal. In those situations, it's pretty each to add this JS to your page (make sure to also include jQuery) to cover all your text/email inputs

$("input[type='text'], input[type='email']").focus ->
    content = @getAttribute("value")
    $(this).val "" if $(this).val() is content

$("input[type='text'], input[type='email']").blur ->
    content = @getAttribute("value")
    $(this).val content if $(this).val() is ""

or if coffeescript isn't your thing

$("input[type='text'], input[type='email']").focus(function() {
    var content;
    content = this.getAttribute("value");
    if ($(this).val() === content) {
      return $(this).val("");
    }
});

$("input[type='text'], input[type='email']").blur(function() {
    var content;
    content = this.getAttribute("value");
    if ($(this).val() === "") {
        return $(this).val(content);
    }
});

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside