Having non removable text in Textarea but still be

2019-08-11 06:01发布

I want to have a textarea that starts with "I am " but it is non removable, like I want it to always be there not a placeholder as well as no one can remove it which gets hidden when text is starting to be written. How would I do this for a textarea.

Code From Fiddle

HTML

<input type="text" class="prefix" value="prefix_" >

Javascript

$('input.prefix').keyup(function(){
   var prefix = 'prefix_';
    if(!(this.value.match('^prefix_'))){
         this.value = prefix;                
    }        
});

$('input.prefix').blur(function(){
   var prefix = 'prefix_';
    if(!(this.value.match('^prefix_'))){
         this.value = prefix;                
    }        
});

1条回答
我只想做你的唯一
2楼-- · 2019-08-11 06:41

The code in your fiddel is close. Instead of replacing the content with prefix replace it with prefix and the value

$('input.prefix').keyup(function(){
   var prefix = 'prefix_';
    if(!(this.value.match('^prefix_'))){
         this.value = prefix + this.value;                
    }        
});

$('input.prefix').blur(function(){
   var prefix = 'prefix_';
    if(!(this.value.match('^prefix_'))){
         this.value = prefix + this.value;                
    }        
});

Example: http://jsfiddle.net/vBBpS/1/

On a side note, you should move the common code to a function.

查看更多
登录 后发表回答