Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it possible to make part of text box read only?

I am trying to show a default text in textbox and make it readonly.

user will be able to add text after that readonly text.

Is it possible by JS and html or css ??

enter image description here

The text READONLY will be readonly and cannot be changed by user. But user can add some text after that . is it possible. I wanto post the text. so i am not going with label.i can split it into 2 . but i am just curious!!

like image 473
zod Avatar asked Aug 13 '13 23:08

zod


2 Answers

Move the text to a normal (<label for>) element before the textbox and add CSS styling to make it look like the it's inside the box.

like image 106
SLaks Avatar answered Oct 01 '22 10:10

SLaks


Any true validation should be done in the backend, but you can assign a value to the textbox's value attribute. On load this will set the defaultValue property of the element in the DOM. Then, on every keyup event, you compare the text's value to that of its original value and modify it as you see fit.

If you insert text into the middle of the value, notice how it inserts the part that doesn't match and keeps the rest of the value, which you had. This could be useful if you paste in a long string and don't want to lose the text.

http://jsfiddle.net/vol7ron/HdpPp/

var $text = $('#text');

$text.on('keyup',function(){
    // Cache some lookups
    var $this    = $(this);
    var _val     = $this.val();           
    var _dv      = $this.prop('defaultValue');
    var _len     = _dv.length;
    var _tmp     = _val.substring( 0, Math.min( $this.val().length, _len ) );
    var mismatch = { found:false, position:0 };

    // Look for character position where two strings differ
    for(var i=0,n=_tmp.length;i<n;i++)
        if ( _tmp[i] != _dv[i] ) {      // compare two characters; true=difference found
            mismatch.found = true;      // set the boolean
            mismatch.position = i;      // store the position
            break;                      // stop looking
        }

    // Original string exists, but with end characters missing
    if ( !mismatch.found && _tmp.length < _len )
        mismatch.position = _len - ( _len - _tmp.length );

    // Insert original string before the mismatch position
    if (mismatch.found || mismatch.position) {
        _val = _val.split('');
        _val.splice( mismatch.position, 0, _dv.substring(mismatch.position) );
        _val = _val.join('');
        $this.val(_val);
    }
});

The easiest way to implement this is to use CSS / label positioning, as others have already suggested.

like image 42
vol7ron Avatar answered Oct 01 '22 09:10

vol7ron