How do I insert a character at the caret with javascript?

前端 未结 6 982
-上瘾入骨i
-上瘾入骨i 2021-01-02 05:55

I want to insert some special characters at the caret inside textboxes using javascript on a button. How can this be done?

The script needs to find the active textbo

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-02 06:33

    In light of your update:

    var inputs = document.getElementsByTagName('input');
    var lastTextBox = null;
    
    for(var i = 0; i < inputs.length; i++)
    {
      if(inputs[i].getAttribute('type') == 'text')
      {
        inputs[i].onfocus = function() {
          lastTextBox = this;
        }
      }
    }
    
    var button = document.getElementById("YOURBUTTONID");
    button.onclick = function() {
      lastTextBox.value += 'PUTYOURTEXTHERE';
    }
    

提交回复
热议问题