How can I simulate a backspace action in a text box?

When I click the button, I just want to simulate the “backspace” in a regular text field by deleting the character to the left of the cursor.

Google and various forums produce truly random results about this. What is the right way to do this?

+3
source share
4 answers

So, I assume that you do not want to focus on text input to remove it.

There are several ways you could try. First get the current contents of the input and delete the last character, and then return the changed string. For example (this code should work):

var txt = $('#myinputtextbox');
txt.val(txt.val().slice(0, -1));

js . , .

+2

Safari (, , Firefox), IE:

  function backspaceAtCursor(id)
  {
    var field = document.getElementById(id);

    if(field.selectionStart)
    {
      var startPos = field.selectionStart;
      var endPos = field.selectionEnd;

      if(field.selectionStart == field.selectionEnd)
      {
        field.value = field.value.substring(0, startPos - 1) + field.value.substring(endPos, field.value.length);

        field.focus(); 
        field.setSelectionRange(startPos - 1, startPos - 1); 
      }
      else
      {
        field.value = field.value.substring(0, startPos) + field.value.substring(endPos, field.value.length);

        field.focus(); 
        field.setSelectionRange(startPos, startPos); 
      }
    }
  }

: backspaceAtCursor('elementid')

+4

Javascript, onClick

var text = document.getElementById(myTxtBox).value;  
text = text.substr(0,text,length-1);
document.getElementById(myTxtBox).value = text;
+1

jQuery , IE, FF, Chrome ( ).

jQuery.fn.extend({
backspaceAtCaret: function(){
  return this.each(function(i) {    

    if (document.selection) 
    {
        this.focus();
        sel = document.selection.createRange();
        if(sel.text.length > 0)
        {
            sel.text="";
        }
        else
        {
            sel.moveStart("character",-1);
            sel.text="";
        }
        sel.select();
    }
    else if (this.selectionStart || this.selectionStart == "0")
    { 
        var startPos = this.selectionStart;
        var endPos = this.selectionEnd;

        this.value = this.value.substring(0, startPos-1) + this.value.substring(endPos, this.value.length);
        this.selectionStart = startPos-1;
        this.selectionEnd = startPos-1;
        this.focus();
    } 
    else 
    {
        this.value=this.value.substr(0,(this.value.length-1));
        this.focus();
    }
  })
}
});
0

Source: https://habr.com/ru/post/1722879/


All Articles