Michael Swarts
Michael Swarts

Reputation: 3921

How can I position a label inside its textfield?

I have many textfields that show instruction text within the textbox (how the default value would look). On focus the color of the text becomes lighter, but doesn't go away until text is entered. When text is erased, the label returns. It's pretty slick. A default value doesn't cut it, because these go away onfocus.

I have it working, but the code is complicated because it relies on negative margins that correspond to the individual widths of the textfields. I want a dynamic solution where the label for its textfield is positioned correctly automatically, probably using a script.

Any help would be greatly appreciated. But I am not looking for default values as a solution.

Thanks.

Mike

Edited to be more precise.

Edited again to provide some simple code that illustrates the effect I am after:

<input style="position: relative; width: 150px; font-size: 10px; font-family: Verdana, sans-serif; " type="text" name="name" id="name"
onfocus="javascript: document.getElementById('nameLabel').style.color='#BEBEBE';"
onkeypress="javascript: if (event.keyCode!=9) {document.getElementById('nameLabel').innerHTML='&nbsp;';}"
onkeyup="javascript: if (this.value=='') document.getElementById('nameLabel').innerHTML='Your&#160;Name';"
onblur="javascript: if (this.value=='') {document.getElementById('nameLabel').style.color='#7e7e7e'; document.getElementById('nameLabel').innerHTML='Your&#160;Name';}"/>
<label id="nameLabel" for="name" style="position: relative; margin-left: -150px; font-size: 10px; font-family: Verdana, sans-serif;">Your Name</label>

Upvotes: 4

Views: 4531

Answers (5)

Gilsham
Gilsham

Reputation: 2276

<script type="text/javascript">
    window.onload = function(){
        inputs = document.getElementsByTagName("input");
        for(i = 0; i < inputs.length;i++){
            var feild = inputs[i];
            if(feild.type == "text"){
                var label = document.getElementById(feild.id + "Label");
                label.style.left = "-" + feild.clientWidth;
            }
        }
    }
</script>

This bit of script should do what you wanted

Upvotes: 0

Tombigel
Tombigel

Reputation: 108

I would have taken a different approach (It's not entirely my idea, but i can't find the source for credit):

1st - Use html5 "placeholder" property.

2nd - Use Modernizr.js to detect support of placeholders in the browser and a simple jQuery script to add support to browsers that doesn't support it.

So, the html will look something like that:

<input type="text" class="placeholder" placeholder="Help Text" />
<textarea class="placeholder" placeholder="Another help text"></textarea>

The css:

.placeholder{color:#ccc;}

And the javascript:

/* Set placeholder for browsers that don't support HTML5 <input placeholder='text'>
 * Depends on Modernizr v1.5
 */
if (!Modernizr.input.placeholder){
    $('input[placeholder], textarea[placeholder]')
        .focus(function() {
            var input = $(this);
            if (input.val() == input.attr('placeholder')) {
                input.val('');
                input.removeClass('placeholder');
            }
        })
        .blur(function() {
            var input = $(this);
            if (input.val() == '') {
                input.addClass('placeholder');
                input.val(input.attr('placeholder'));
            }

        })
        //Run once on load
        .blur();

    // Clear all 'placeholders' on submit
    $('input[placeholder], textarea[placeholder]').parents('form').submit(function() {
        $(this).find('[placeholder]').each(function() {
            var input = $(this);
            if (input.val() == input.attr('placeholder')) {
                input.val('');
            }
        });
    });
}

Upvotes: 3

Emily
Emily

Reputation: 10088

Do you mean like this? But instead of 'required' it would have the label?

I used a jQuery solution where I set the value of the input to 'required'. The input has a class of gray so the default text is lighter.


Edit after comment

Instead of using focus, you can change the input values on keydown and keyup.

$('.required_input').keydown(function()
{
    if (this.value == 'required')
    {
        $(this).val('').removeClass('gray');
    }
} );

$('.required_input').keyup(function()
{
    if (this.value == '')
    {
        $(this).val('required').addClass('gray');
    }
} );

$('.required_input').blur(function()
{
    if (this.value == '')
    {
        $(this).val('required').addClass('gray');
    }
} );

Upvotes: 0

Cᴏʀʏ
Cᴏʀʏ

Reputation: 107606

Here's one that I borrowed from somewhere:

$(function() {

    // Give the textbox a watermark
    swapValues = [];
    $('.your_input_class').each(function(i){
        $(this).val("Please enter xyz");
        swapValues[i] = $(this).val();
        $(this).focus(function(){
            if ($(this).val() == swapValues[i]) {
                $(this).val("").css("color", "#333");
            }
        }).blur(function(){
            if ($.trim($(this).val()) == "") {
                $(this).val(swapValues[i]).css("color", "#ccc");
            }
        });
    });

});

And then for your input box:

<input class="your_input_class" type="text" value="" />

It remembers the value that is stored in it when the page loads (well, I'm setting mine directly in the JS) and it also changes the color when it's focused/not focused.

Upvotes: 0

Jimmy Chandra
Jimmy Chandra

Reputation: 6580

What you are asking here is probably what is called textbox watermark.

For this, you usually don't use a label (control) inside a textfield. Instead you replace the content of the textfield when the real content of the text field is empty with some text using certain CSS property and then remove it once you blur out (w/ additional check to see if the text inside the textbox itself is the same as the watermark text. If it is, blank the field again.)

Try this. It's pretty simple implementation of this using jquery and css.

Upvotes: 0

Related Questions