jQuery: textarea default value disppear on click

前端 未结 8 1205
Happy的楠姐
Happy的楠姐 2021-02-04 16:40

I want a textarea with some default text. When the user clicks in the textarea the default text should be deleted. How can I make value of a textarea disappear on click?

<
8条回答
  •  故里飘歌
    2021-02-04 17:25

    This should work:

    $('#txt')
        .focusin(function() {
            if ( this.value == 'Write something...' ) {
                this.value = '';    
            }
        })
        .focusout(function() {
            if ( this.value == '' ) {
                this.value = 'Write something...';    
            }
    });
    

    Live demo: http://jsfiddle.net/g7UKN/1/


    Update:

    This should do it:

    $('#txt')
        .each(function() {
            $(this).data('default', this.value);
        })
        .focusin(function() {
            if ( this.value == $(this).data('default') ) {
                this.value = '';    
            }
        })
        .focusout(function() {
            if ( this.value == '' ) {
                this.value = $(this).data('default');    
            }
    });
    

    Live demo: http://jsfiddle.net/g7UKN/2/

提交回复
热议问题