jQuery: textarea default value disppear on click

前端 未结 8 1327
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:23

    You need two handlers, one for when the element gets focus and one for when it loses it. When it gets focus, check to see if the value is only space characters and, if so, set the value to the default.

    $('#textarea').focus( function(){
            var $this =$(this);
            if($this.val() == 'This should be removed..'){
                 $this.val('');
            }
    }).blur(function() {
            var $this = $(this);
            if ($this.val().match(/^\s*$/) { // matches only spaces or nothing
                 $this.val('This should be removed..');
            }
    });
    

提交回复
热议问题