Dynamically Modifying Input Elements on Click

Sometimes it’s necessary to modify an input form element when a user clicks on that element. In some cases, the form element can contain information regarding what information is appropriate, or what format is expected. The most common example is showing “mm/dd/yyyy” in a text-based date field and automatically removing that information when a user clicks on the field.

This example will show a login form which is pre-populated with some helper information. When the user clicks on it, the information is modified. An additional feature to this code is that the password textbox is dynamically modified from a “text” type to a “password” type, hiding all of the text that the user enters.

<form action="#" method="post"> <p>Please sign in.</p> <div><label for="email">Email</label><br /> <input type="text" name="email" id="email" value="" /></div> <div> <label for="password">Password</label><br /> <input type="password" name="password" id="password" value="" /> </div> <div><input type="submit" name="submit" value="Login" /></div> </form>

<script type="text/javascript"> //required: JQuery //automatically performs the following on page ready $(document).ready(function(){ //sets the email text to the following: $("#email").val("Email you used to create your account") .css({color:"#ccc"}) //changes the color to be hint-like .click(function(){ //changes the text color back to black, //clears the helper text $(this).css({color:"#000"}).val(""); });

    //save the original password box
    var inptPassword = $("#password");

    //replace the password box with a normal text box
    $("#password").replaceWith($('&lt;input type="text" /&gt;').attr({
                    name:"password",
                    id:"password",
                    value:"Password"
            }).css({color:"#ccc"})
            .click(
                    function(){
                            //replace the textbox-style password box
                            //with the original
                            $(this).replaceWith(inptPassword);
                    }
            ).keyup(
                    function(){
                            var val = $(this).val();
                            if($(this).attr("type") == "text"){
                                    $(this).replaceWith(twdc_inptPassword);
                                    twdc_inptPassword.focus()
                            }
                    }
            ));

}); </script>

Note: Instead of setting a color in Javascript, you should use css classes and the addClass/removeClass methods for when you load and click on a text box.

Latest Posts