SiteKickr Web Development

Labelling form fields without using labels – Method II

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(''); });
});