Help please, changing form on click.

Discussion in 'JavaScript' started by Josh-H, Jul 31, 2008.

  1. #1
    Hello.

    What I'm trying to do is have my form display the text "Your account password" in standard text until you click on the form field where it changes to a password field type and is empty. I've got this to work when you click into the field using this javascript that I edited:

    <input type='text' name='password' id='password' class='formbox' value='Your account password' onclick=\"if(this.type == 'text') this.type='password'; if(this.value == 'Your account password') this.value='';\" onblur=\"if(this.value.length == 0) this.value='Your account password'; if(this.value == 'Your account password') this.type='text'; \" />
    Code (markup):
    Problem is that the form type doesn't change when I tab into the field from the field above. Therefore the password is displayed as normal text. A major problem obviously.

    +REP to anyone who helps me.

    Thank You.
     
    Josh-H, Jul 31, 2008 IP
  2. rohan_shenoy

    rohan_shenoy Active Member

    Messages:
    441
    Likes Received:
    20
    Best Answers:
    0
    Trophy Points:
    60
    #2
    Hope you are comfortable with DOM manipulations ;)
    
    <script type="text/javascript">
    function text2password()
    {
    //cross-browser(recommended)
    var field_container=document.getElementById("field_container");
    field_container.removeChild(document.getElementById("password"));
    var new_field=document.createElement("input");
    new_field.setAttribute("type","password");
    new_field.setAttribute("id","password");
    field_container.appendChild(new_field);
    new_field.focus();
    
    
    /* works in Mozilla only, not IE, and may not in opera and safari: so not recommended
    document.getElementById("password").setAttribute("type","password");
    document.getElementById("password").type="password";
    */
    }
    </script>
    
    Code (javascript):

    The HTML:
    
    <div id="field_container">
    <input type="text" value="Your Password" id="password" onfocus="text2password()" />
    </div>
    
    HTML:
     
    rohan_shenoy, Jul 31, 2008 IP
  3. Josh-H

    Josh-H Active Member

    Messages:
    406
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    55
    #3
    Thank You for that but I managed to sort it by changing it from onclick= to onfocus= :) Was just simpler for me to do it that way. +REP regardless.
     
    Josh-H, Aug 1, 2008 IP