Javascript to make input field in edit mode(insert mode)

前端 未结 4 1809
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-12 01:19

How is it possible to make a input field editable in javascript. I mean onFocus putting it in insert mode so that values can be overwritten. Any suggestions ???

4条回答
  •  悲&欢浪女
    2021-01-12 01:46

    You can try to mimic Insert mode by rewriting the input value on keyup :

    var input = $('input'); // your input element
    
    Event.observe(input, 'keydown', function(e) { // event handler
       input._lastvalue = input.value;
    });
    
    Event.observe(input, 'keyup', function(e) { // event handler
        if(input.value == input._lastvalue) return;
        if(input.value.length <= input._lastvalue.length) return;
        var caretPos = doGetCaretPosition(input);
        input.value = input.value.slice(0,caretPos) + input.value.slice(caretPos+1);
        doSetCaretPosition(input, caretPos);
    });
    

    Here is a demo : http://jsfiddle.net/z6khW/

提交回复
热议问题