Search code examples
jqueryhtmlcsscursor-positioninputbox

Add non-editable text after cursor in input box


I'm trying to add non-editable text after the cursor in a text field/input box as to achieve the following:

1) The text before the cursor is editable 2) The text after the cursor is not editable and moves right/left as the text to the left is added/removed

INPUT FIELD: [editabletexthere{cursorhere}non-editabletexthere ]

Here is the code to my input box thus far:

<input id="edit_input" type="text" autocapitalize="off" autocorrect="off" spellcheck="false" autofocus onfocus="this.value = this.value;" value="editabletext" style="width:100%;"></input>

I feel like the values in the input should be housed within a span and for the second span simply to be stylized with contenteditable= false;. I would also like to stylize the non-editable text to a different color. Any help would be much appreciated. Thank you.


Solution

  • This might not be the best solution, it's kind of a hack but it works fine. The idea is to create a div that looks like an input box with inside 2 span, and you make one of them editable.

    div {
        border: 1px solid #999;
        padding: 5px;
        width: 100%;
    }
    
    span {
        width: auto;
        outline: 0;
    }
    
    span.trailing {
        color: grey;
    }
    <div>
        <span contenteditable="true" id="edit_input_fake">Input</span>
        <span class="trailing">Trailing text</span>
      </div>

    You can create an <input type="hidden"> where you copy the content of the first span (maybe the second one as well?) on event keydown/change if needed.

    JSFiddle available here: http://jsfiddle.net/c6f7ommh/1