Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add a default text to the beginning of an html text area?

Im building a personal little social network. As part of the design, all statuses should begin with a default text that shouldn't change, similar to "Hi, my name is…" and then the user finishes the rest. Kind of like an HTML5 placeholder that doesn't go away. What would be the best way to accomplish this?

like image 251
Voltron Avatar asked Nov 30 '25 03:11

Voltron


2 Answers

Please refer this fiddle If it serves the purpose, then please find the code below.

Markup:

<textarea id='status'>
Hi, my name is...
</textarea>

JavaScript:

document.querySelector('#status').addEventListener('input', function(e){
    var defaultText = 'Hi, my name is...',
        defaultTextLength = defaultText.length;
    if(this.selectionStart === this.selectionEnd && this.selectionStart defaultTextLength {
        this.value = defaultText;
    }
});
like image 90
Sarbbottam Avatar answered Dec 02 '25 17:12

Sarbbottam


Note: For some dumb reason, I assumed jQuery (note that you do not need jQuery for this, but makes it a little easier).

Here is one solution uses a combination of text-indent and an absolutely positioned <span> (for the prefix part).

Demo: http://jsfiddle.net/4YzZy/


$('textarea.withprefix').each(function() {
  var prefix = $('<span/>')
              .text($(this).data('prefix'))
              .addClass('prefix')
              .appendTo('body')
              .css({
                  left: $(this).position().left + 'px',
                  top: $(this).position().top + 'px',
              });
  $(this).css({textIndent: prefix.outerWidth() + 'px'});
});
textarea, span.prefix {
    font-family: arial; /* change these as needed, but ensure that the textarea and the span use the same font */
    font-size: 1em;
    font-weight: normal;
    padding: 2px;
    border-width: 1px;
}
span.prefix {
    position:absolute;   
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea class="withprefix" data-prefix="Hi There, "></textarea>
like image 24
techfoobar Avatar answered Dec 02 '25 15:12

techfoobar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!