Here's a handy method I came up with to "move" labels inside form fields, to save real estate. It also degrades gracefully if the user does not support JavaScript. It depends on jQuery.

Example form

<form action="" method="post">
    <div class="field">
        <label for="name">Name</label>
        <input type="text" name="name" id="name" />
    </div>
    <div class="field">
        <label for="email">Email</label>
        <input type="text" name="email" id="email" />
    </div>
    <div class="field">
        <label for="message">Questions</label>
        <textarea name="message" id="message"></textarea>
    </div>
    <div class="form-controls-no-js">
        <input type="image" src="/img/submit.png" alt="Submit" />
    </div>
</form>

 

jQuery

$('form label').each(function() { $(this).next().val($(this).html()); $(this).hide(); });

 

To take it a step further, if we want these prefilled values to be wiped out when the input takes the focus:

$('form label').each(function() {
    $(this).hide();
    $(this).next().val($(this).html());
    $(this).next().focus(function() { if($(this).val() == $(this).prev().html()) $(this).val(''); });
});

Tags:

1 Comment

  1. You may also wish to check that a given field is empty before prefilling it with the label value. This is especially important if you have server side validation which sends a user back to the form on failure.

    if ($(this).next().val() != '')

Leave a Reply

Your email address will not be published. Required fields are marked *