jQuery function to toggle input value

In this example below you will see how to do a jQuery function to toggle input value with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by patrickkahl, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright patrickkahl ©

Technologies

  • HTML
  • CSS
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>jQuery function to toggle input value</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js" type="text/javascript"></script>


    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">

  
      <link rel="stylesheet" href="css/style.css">

  
</head>

<body>

  <input type="search" value="Search" />
  <script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>

  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/patrickkahl/jquery-function-to-toggle-input-value-BvqtD */
body {
  margin: 50px;
  text-align: center;
}


/*Downloaded from https://www.codeseek.co/patrickkahl/jquery-function-to-toggle-input-value-BvqtD */
;(function($){  

  $.fn.ToggleInputValue = function(){
    return $(this).each(function(){
      var Input = $(this);
      var default_value = Input.val();

      Input.focus(function() {
        if(Input.val() == default_value) Input.val("");
      }).blur(function(){
        if(Input.val().length === 0) Input.val(default_value);
      });
    });
  }

  /* ================================================== */

  $(window).load(function() {
    $('input').ToggleInputValue();
  });
  
}(jQuery));

Comments