Friday, June 28, 2013

Placeholder for Help Text

Since the placeholder (help text) feature of HTML 5 is supported by IE, we can create our own help text by using jQuery.

Assumed that on the .cshtml page, we have a TextArea control with ID ="Description".

Step 1: Set the help text to the control, and set the text color to grey
  var promp = " Please enter description here...";
    $("#Description").text(promp);
    $("#Description").css("color", "grey");

Step 2: Set cursor to the first position when the control get focus
     //SET CURSOR POSITION
        $.fn.setCursorPosition = function (pos) {
            this.each(function (index, elem) {
                if (elem.setSelectionRange) {
                    elem.setSelectionRange(pos, pos);
                } else if (elem.createTextRange) {
                    var range = elem.createTextRange();
                    range.collapse(true);
                    range.moveEnd('character', pos);
                    range.moveStart('character', pos);
                    range.select();
                }
            });
            return this;
        };

        $("#Description").on('focus', function () {
            $("#Description").setCursorPosition(0);
        });

Step 3: Clear the help text and reset text color to black, when user clicks on the control or presses key.

       $("#Description").one('keydown',function () {
            $("#Description").text("");
            $("#Description").css("color", "black");                   

        });

        $("#Description").one('click', function () {
            $("#Description").text("");
            $("#Description").css("color", "black");
        });

Step 4: It's very important to clean the help text when the form is submit or to check if user has input new text (if the field is set to require). In this case, we assume that the field is a required field. So, when user clicks Submit button, the below script will perform:

<script type="text/javascript">
   
    $(document).ready(function () {
     
         var promp = " Please enter description here...";
       
          $("form").submit(function () {
                      
            if ($("#Description").text() == promp) {
                $("input[type=submit]").removeAttr("disabled");
                alert("Please enter description");
                $("#Description").focus();
                return false;
            }         
            return true;       
                         
           });
    });


</script>

No comments:

Post a Comment