I have been using Jquery for a few months now, and have completely fallen in love with it. I’ve probably looked at hundreds of different pages, blogs, posts, plugins, and tricks over the time I’ve spent learning it. Here are a few of my favorite things to use it for.
Putting text labels in a password field
Password inputs mask the text in them, so having “Enter Password” inside the field won’t do much good. We can’t change the type of input on the fly, but we can make it disappear, and have another appear… Here’s how I’ve done this:
1. $(".passflip").click(function() {
2. if ($(this).attr("type") == "text") {
3. $(this).hide();
4. $("#"+$(this).attr("id").slice(1)).show().focus();
5. }
6. });
7. $(".passflip").show();
8. $(":password").hide();
And the HTML code:
1. <input id="Tuser_pass" class="input passflip" style="display: none;"
name="Tpwd" size="20" type="text" value="Enter Password" />
2. <input id="user_pass" class="input" name="pwd" size="20"
type="password" />
What we’re looking at here may seem messy at first, especially line 4 of the javascript code. Its not that bad. It takes the id of the passflip element that we clicked, removes the first character (giving us user_pass in this case), and shows and sets focus to that element. To the user, that text input will have “transformed” to a password input seamlessly.
The text input has an initial display of “none”. Also, in lines 7 and 8, we then hide all the password inputs (which are set to visible on page load), and show all the passflip inputs. This ensures that for those without javascript enabled, they will still be able to use the form as intented. The only difference, is that they won’t see the “Enter Password” information in the input, it will just be blank.
Friendly one time “clear this” function
1. $(".clearThis").click(function() {
2. if ($(this).val() == $(this).attr("title")) $(this).val("");
3. });
4. $("#username").val($("#username").attr("title"));
and the html
1. <input type="text" name="user_email" id="user_email"
class="input clearThis" size="20" tabindex="20"
title="ENTER EMAIL" />
The value of this little gem may not be apparent at first, but it’s a perfect companion to the above mentioned function, and fails very gracefully on non-javascript enabled machines as well.
Instead of setting the value of the text box to display “ENTER EMAIL”, we simply set the title. What happens then, if javascript is enabled, is that the value will be set, displaying instructions to the user. the clearThis click function then checks to see if the two match, and if so, its likely the first time that input was clicked, and it clears the box for user input. If javascript is not enabled, the clearThis click function obviously cannot work, but the text input won’t have anything in it to clear anyway, so we have a double win.
This is all I have for now. I’ll post more sometime next week. Love live JQuery!