user3618465
user3618465

Reputation: 1

Input text toggle

I'm trying to create a text input where the value i.e "Client's Name" is shown and then when it is clicked it disappears, then if nothing has been typed and the user clicks off "Client's Name" is displayed again. I have achieved this, but, if the user Types something and then changes their mind, deletes the text they just inputted, then clicks off, "Client's Name" does not appear again. I would be very grateful for the help please.

$(function() {
    $('#InvClientsName').click(function(){
        if( $('#InvClientsName').attr("value") == "Client's Name" ) {
            $('#InvClientsName').attr("value", "");
         }
    });
    $('#InvClientsName').outside('click', function(e) {
        if( $('#InvClientsName').attr("value") == "" ) {
            $('#InvClientsName').attr("value", "Client's Name");
        }
    });
});

Upvotes: 0

Views: 39

Answers (1)

scrowler
scrowler

Reputation: 24406

There are a couple of things you need to consider here:

  1. When a user clicks on your field (focusin event), the text should blank out, but this should probably only happen if they haven't put any custom text into the field already
  2. When a user clicks out of the field (focusout event), the text should revert to the default text, but only if the text is not empty

So, you can try this:

HTML:

<input type="text" id="InvClientsName" value="Hello world!">

jQuery:

var defaultText = $('#InvClientsName').val(); // grabs the default text field value on page load

$('#InvClientsName').focusin(function() { // when entering the text field by click or tabbing
    if($(this).val().trim() == defaultText) // if it's default text
        $(this).val(''); // blank it out
});

$('#InvClientsName').focusout(function() { // when leaving the text field
    if($(this).val().trim() == '') // if the field is blank
        $(this).val(defaultText); // set the value to default
});

However, this behaviour is very similar to the placeholder attribute, and you could simply replace this entire process with:

<input type="text" id="InvClientsName" value="" placeholder="Hello world!">

Here's a fiddle so you can see the differences.

Upvotes: 1

Related Questions