简体   繁体   中英

How to make textarea editable?

I have a textarea which converts English to Hindi onkeyup event. But when I move the caret backward for editing, the first letter I type converts to Hindi and the caret moves to the end of the string. Is possible to store the caret at the same point within the textarea , so that it doesn't move to the end of the string?

The issue with this is that you are overwriting the value of the textarea every key up which is what makes the caret move.

You will want to get the value of the caret before you replace the text and set it again after the replace.

Stackoverflow Answer: Get Caret Position - Code from linked answer below unaltered

function getCaret(el) { 
  if (el.selectionStart) { 
    return el.selectionStart; 
  } else if (document.selection) { 
    el.focus(); 

    var r = document.selection.createRange(); 
    if (r == null) { 
      return 0; 
    } 

    var re = el.createTextRange(), 
        rc = re.duplicate(); 
    re.moveToBookmark(r.getBookmark()); 
    rc.setEndPoint('EndToStart', re); 

    return rc.text.length; 
  }  
  return 0; 
}

Stackoverflow Answer: Set Caret Position - Code from linked answer below unaltered

function SetCursorPosition(pos)
{
    // HERE txt is the text field name
    var obj=document.getElementById('<%= txt.ClientID %><%= txt.ClientID %>');

    //FOR IE
    if(obj.setSelectionRange)
    {
        obj.focus();
        obj.setSelectionRange(pos,pos);
    }

    // For Firefox
    else if (obj.createTextRange)
    {
        var range = obj.createTextRange();
        range.collapse(true);
        range.moveEnd('character', pos);
        range.moveStart('character', pos);
        range.select();
    }
}

There are a few other methods to get around this by avoiding the replacing all the text on a key up event and move it to a button press, blur/unfocus or something else. This allows you not to worry about any caret position resetting to the end.

The only real disadvantage I see for moving to another event to trigger text change is simply that it is not instantaneous.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM