I have a signup form with 3 fields:
Username
Password
On most browsers when a user clicks on a particular field, the placeholder value displayed is blanked out so the user can type and if they type nothing and come out of the field the placeholder text re-appears. Anyway some browsers e.g. chrome don’t hide the placeholder text onfocus so I had to write some javascript to take care of this.
I’m quite new to javascript but to me the code I’ve written to deal with this doesn’t seem right. I have a feeling it could be shorter and better.
For each field I have this inside a document ready function:
$("#field_id").focusin(function() {
$(this)[0].placeholder = "";
});
$("#field_id").focusout(function() {
$(this)[0].placeholder = "Enter email";
});
My html:
<p><input class="signupFields" data-validate="true" id="user_username" name="user[username]" placeholder="Username" size="30" type="text" /></p>
<p><input class="signupFields" data-validate="true" id="user_email" name="user[email]" placeholder="Email" size="30" type="text" /> </p>
<p><input class="signupFields" data-validate="true" id="user_password" name="user[password]" placeholder="Password" size="30" type="password" /> </p>
So imagine that times 3 .. Seems like a lot of code for such a simple requirement. Also I really don’t like the fact that I’m trying to mimic javascripts document.getElementById. There must be a way I can do this in a more jQuery like way. Not liking the [0].
Can any body give me an example of a cleaner way of doing this exact same thing?
Kind regards
I’d suggest that you don’t need to worry about this, but to remove the placeholder text on focus (and to restore the
placeholderonblur) I’d advise the following:JS Fiddle demo.
The only reason to use the
$(this)[0]notation is to ‘break out’ from the jQuery-fied$(this)object back to the native DOM node. To avoid doing that, it’s easier to justthis:JS Fiddle demo.
References:
blur()(jQuery).focus()(jQuery).data()(jQuery).focus()(jQuery).removeAttr()(jQuery).removeAttribute().