JQuery: in focus in the text box, delete the default text + change color, on unocus - put the text back

This is a very common problem that we see on stackoverflow, facebook, etc.

You often want to give the user some text to direct him to what needs to be done, but you want the text to disappear the moment he clicks on it.

What is the easiest way to do this through jQuery? This seems like a fairly common use case.

+3
source share
5 answers

, , , " " - , . jQuery, , .

: http://code.google.com/p/jquery-watermark/

+3

script :

$(document).ready(function () {

    searchInput = $('#search-input');
    searchDefault = 'Please enter text';

    searchInput.click(function () {
        if($(this).val() == searchDefault)
            $(this).val('');
    });

    searchInput.blur(function () {
        if($(this).val() == '')
            $(this).val(searchDefault);
    });

});

, .

+3

- jsfiddler.net

JQuery

$(function() {
    $('#placeholderText').val("Placeholder")
        .focusin(function(){
            if($(this).hasClass('initialClass'))
                $(this).removeClass('initialClass').
                    addClass('normalClass').val('');                
        })
        .focusout(function(){
            if($(this).hasClass('normalClass') && $(this).val() == '')
                $(this).removeClass('normalClass').
                    addClass('initialClass').val('Placeholder');    
        });
});

CSS

.initialClass {
    color: #999999;
}

.normalClass {
    color: #000000;
}

HTML:

Click on me: <input id="placeholderText" type="text" class="initialClass" />
+3

, toggleVal. jquery, , . http://jquery.kuzemchak.net/toggleval.php

HTML:

<label for="field1">Some text to explain the text area.</label>
<textarea id="field1" name="textarea1"></textarea>

CSS

.toggleval {
  font-style: italic;
  color:#333;
}
.tv-changed, .tv-focused {
  font-style: normal;
  color:#000;
}

Javascript:
$('.toggle').toggleVal({
    populateFrom: "label",
    removeLabels: true
});
+1

, - , ...

 $(this).focusin(function () {
       }).focus(function () {
             if ($(this).val() == 'Enter a comment') {
                  $(this).select();
             }
          }).val("Enter a comment").select();
 });                        
0
source

Source: https://habr.com/ru/post/1762987/


All Articles