Switching jQuery input value

I use this code to switch the values โ€‹โ€‹of my onFocus and Blur inputs:

$('input, textarea').focus(function() {
            value=$(this).val();
            $(this).attr("value","")};
        });
        $('input, textarea').blur(function() {
            if($(this).val()=="") {
                $(this).val(value);
            }
        });

The only problem is that when I enter something into these inputs, redefine after entering into another field, the field becomes empty. Is there a way to edit this code to ban it?

An example for you here :)


I tried something like this, but this was not what I want:

$('input, textarea').focus(function() {
            value=$(this).val();
    if($(this).val(value)) {
            $(this).attr("value","");
        });
        $('input, textarea').blur(function() {
            if($(this).val()=="") {
                $(this).val(value);
            }
        });
+3
source share
5 answers

You need to set the initial value and check for it.

$('input, textarea').each(function(){
    // initial storing of the pre-defined value
    $(this).data('initial', this.value);
}).focus(function(){
    var $this = $(this);
    // on focus if the value of the field is still the initial then clear it
    if ( (this.value) == $this.data('initial') )
      this.value = '';
}).blur(function(){
    var $this = $(this);
    // on blur if the value is still cleared then restore the initial 
    if ( (this.value) == '' )
        this.value = $this.data('initial');
})

Demo : http://jsfiddle.net/EMYmG/2/


Update

, defaultValue, . ( )

$('input, textarea').focus(function(){
        // on focus if the value of the field is still the initial then clear it
        if ( (this.value) == this.defaultValue )
          this.value = '';
    }).blur(function(){
        // on blur if the value is still cleared then restore the initial 
        if ( (this.value) == '' )
            this.value = this.defaultValue;
    })

: http://jsfiddle.net/PjsRQ/

+3

. , .

, . , ( DOM ).

A jQuery -, , , .

+1

- : http://jsfiddle.net/Ajcmq/

, : , , , , .

, dfault , : D.

+1
0

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


All Articles