最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - is it possible to make part of text box read only? - Stack Overflow

programmeradmin2浏览0评论

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 ??

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!!

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 ??

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!!

Share Improve this question edited Aug 14, 2013 at 0:04 zod asked Aug 13, 2013 at 23:52 zodzod 12.4k25 gold badges73 silver badges107 bronze badges 3
  • Can you elaborate on your use case? Or do you just want a blind answer? Also what is this "READONLY WRITABLE"? – No Results Found Commented Aug 13, 2013 at 23:56
  • 1 One approach is to manage the content of the textbox by monitoring key events, and prevent a fixed/"read only" part of the textbox from being deleted. – TGH Commented Aug 14, 2013 at 0:05
  • 3 FYI: If you want to read/add the "readonly" value, just add it manually server-side. You cannot guarantee that the text will be uneditable, it's for the UI only. People can "hack" it very easily. You know that right? – No Results Found Commented Aug 14, 2013 at 0:05
Add a ment  | 

4 Answers 4

Reset to default 2

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.

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 pare 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/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] ) {      // pare 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.

var InputMask = {
init: function () {
    var divMask = document.getElementById("readonly");
    var inputField = document.getElementById("myInput");

    InputMask._input = inputField;
    InputMask._pos = 0;
    // resets the form
    inputField.value = "";

    divMask.addEventListener('click', InputMask.focusHandler, false );
    inputField.addEventListener('focus', InputMask.focusHandler, false );
    inputField.addEventListener('keydown', InputMask.keyInput, false );

},

focusHandler: function(event){
    InputMask._input.focus();

    var backup = InputMask._input.value.substr(20) || "";

    InputMask._input.value="                    " + backup;
},

keyInput: function ( event ) {
    var length_invalid = (InputMask._input.value.length == 20 ) ? true : false;
    var realString = InputMask._input.value.substr(20);
    var realLength = realString.length;

    // fix to mouse selection delete
    if ( InputMask._input.value.length < 20 ) {
        InputMask._input.value="                    ";
    }

    // backspace code = 8
    if (event.keyCode == 8 && length_invalid ) event.preventDefault();

    // left arrow key = 37
    if ( event.keyCode == 37 && (realLength + InputMask._pos) == 0 ) {
        event.preventDefault();
    } else if (event.keyCode == 37 && ( InputMask._pos >= (0 - realLength))) {
        InputMask._pos--;
    }

    // right arrow key = 39
    if ( event.keyCode == 39 && InputMask._pos < 0) InputMask._pos++;        

    // enter = 13
    if ( event.keyCode == 13) {
        alert ( "Input Value: ["+ InputMask._input.value.substr(20) +"]");

        // reset
        InputMask.reset();
    }
},
reset: function(){
    var field = InputMask._input;

    field.value = "";
    field.blur();
}
};

InputMask.init();

jsFiddle

This code uses the CSS styling, some text spacing in the input value and event handlers. I didn't write a full handling function for mouse selection, which currently lets the user select the white spaces and delete it (or even backspace it, if there is a string typed), but will insert the 20 spaces if any key is pressed and the length is < 20.

When you press the arrow keys, it will calculate where the cursor is, and based on that, let you move it or not (just simple preventDefault). And on ENTER, will display the value without the filling spaces.

The good thing about the overlapping div is that you can use different text colors, backgrounds, etc (div styling).... All you need to do is set the amout of white spaces to make it appear that the div is inside the input.

Of course this is not cross-browser, you'll have to do all the declaration checks and event handling checks on your own, but I think that's basically what you wanted, right?

Just somethin I whipped up. Hope it helps

 <div style="position:absolute; z-index:1; top:1px; width:270px; border:2px; border:1px 
 solid black;">type here:</div>

 <input style="position:absolute; z-index:2; top:1px; width:200px; left:70px; border:0px   
 solid black;"/>
发布评论

评论列表(0)

  1. 暂无评论