简体   繁体   English

如何通过在最近使用的文本框中的 cursor 上单击按钮来插入文本?

[英]How can I insert text via button click at the cursor in the most recent textbox used?

I have a form with multiple text boxes and a set of buttons.我有一个带有多个文本框和一组按钮的表单。 Using the Javascript below, I am able to click a button and insert text into one of the named boxes.使用下面的 Javascript,我可以单击一个按钮并将文本插入其中一个命名框。

Is it possible to insert text into the most recent/active textbox when a button is clicked?单击按钮时是否可以将文本插入最新/活动的文本框?

Currently I have this, but it's using the specific ID of a text box, rather than the most recently used/active one;目前我有这个,但它使用的是文本框的特定 ID,而不是最近使用/活动的 ID;

   $( 'input[type=button]' ).on('click', function(){
      var cursorPos = $('#my_text_box').prop('selectionStart');
      var v = $('#my_text_box').val();
      var textBefore = v.substring(0,  cursorPos );
      var textAfter  = v.substring( cursorPos, v.length );
      $('#my_text_box').val( textBefore+ $(this).val() +textAfter );
    });

Example on JSFiddle for more clarity; JSFiddle 上的示例更清晰;

http://jsfiddle.net/bd1xf0sj/1/ http://jsfiddle.net/bd1xf0sj/1/

The idea being that depending upon which text box you're in when the button is clicked, instead of using the ID of a certain textbox.这个想法取决于单击按钮时您所在的文本框,而不是使用某个文本框的 ID。 The idea being that the buttons can be clicked and any textbox can be used.这个想法是可以单击按钮并且可以使用任何文本框。

You can create a variable to store the most recent textbox and update it whenever a textbox is focused like this:您可以创建一个变量来存储最新的文本框,并在文本框像这样聚焦时更新它:

let currentInput = $('#text1');
$(document).on('focus', 'textarea', function() {
  currentInput = $(this);
})

Then use this variable to update text just like you're doing with your #my_text_box :然后使用此变量来更新文本,就像您对#my_text_box所做的那样:

$( 'input[type=button]' ).on('click', function(){
  let cursorPos = currentInput.prop('selectionStart');
  let v = currentInput.val();
  let textBefore = v.substring(0,  cursorPos );
  let textAfter  = v.substring( cursorPos, v.length );
  currentInput.val( textBefore + $(this).val() + textAfter );
});

Fiddle小提琴

Update : Some modification to preserve the cursor position after insert text:更新:插入文本后保留 cursor position 的一些修改:

 let currentInput = document.getElementById('text1'); $(document).on('focus', 'textarea', function() { currentInput = this; }) $( 'input[type=button]' ).on('click', function(){ let cursorPos = currentInput.selectionStart; let v = currentInput.value; let textBefore = v.substring(0, cursorPos ); let textAfter = v.substring( cursorPos, v.length ); currentInput.value = textBefore + this.value + textAfter; cursorPos += this.value.length; currentInput.focus(); currentInput.setSelectionRange(cursorPos, cursorPos); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form> <textarea id="text1" cols="40" rows="3"></textarea> <textarea id="text2" cols="40" rows="3"></textarea> <textarea id="text3" cols="40" rows="3"></textarea> <textarea id="text4" cols="40" rows="3"></textarea> <br> <input type="button" value="one" /> <input type="button" value="two" /> <input type="button" value="three" /> </form>

You can track the current state of the inputs focus using a data-attribute set to a boolean value true or false within the input elements HTML.您可以使用在输入元素 HTML 中设置为 boolean 值truefalsedata-attribute来跟踪输入焦点的当前 state。

Start by defining the first data-current attribute to true , every other one to false .首先将第一个data-current属性定义为true ,每隔一个属性定义为false This way there is a default setting to true .这样,默认设置为true Then we run an event to check focus on the textarea elements.然后我们运行一个事件来检查对textarea元素的关注 If the textarea is focused on, we remove all instances of the selectors data-current values and set them all to false , we then set our current event targets data-current value to true .如果textarea关注,我们删除选择器data-current值的所有实例并将它们全部设置为false ,然后我们将当前事件目标data-current值设置为true

Then on the click event for the buttons , we check our textarea element iterating over them and run a conditional that checks their data-current value , we find the one set to true and then assign its value to the buttons value .然后在按钮单击事件中,我们检查迭代它们的textarea元素并运行检查它们的data-current条件,我们找到设置为true的那个,然后将其分配给按钮值

 $('textarea').focus(e => { let $this = e.target; $('textarea').each((i, el) => { if(el.dataset.current === 'true'){ el.dataset.current = false; } $this.dataset.current = true; }) console.log(`Selected TextArea's id: ${$this.id}`) }) $('input[type=button]').click(function(){ const $this = $(this); const $ta = $('textarea'); $ta.each((i, el) => { // do not retain previously set values when a new button // is selected on a different focused textarea el.dataset.current === 'true'? el.value = $this.val(): el.value = ''; /* // retain previously set values in TA's on button click // when new textarea is focused el.dataset.current === 'true'? el.value = $this.val(): null; */ }) })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form> <textarea id="text1" data-current="true" cols="40" rows="3"></textarea> <textarea id="text2" data-current="false" cols="40" rows="3"></textarea> <textarea id="text3" data-current="false" cols="40" rows="3"></textarea> <br> <input type="button" value="one" /> <input type="button" data-current="false" value="two" /> <input type="button" data-current="false" value="three" /> </form>

It's actually a simple and fun exercise to solve, there are many approaches to solve this particular problem, though I will suggest mine.这实际上是一个简单而有趣的练习来解决,有很多方法可以解决这个特定问题,尽管我会建议我的。

Here's the link to solved jsFiddle example.这是解决的jsFiddle示例的链接。

Explanation:解释:

Step 1: Add focus event listener on all textarea .第 1 步:在所有textarea上添加focus事件侦听器。

Step 2: On textarea focused, remove the class last-focused from existing last-focused.textarea elements.第 2 步:在textarea集中,从现有last-focused.textarea元素中删除 class last-focused元素。

Step 3: Add last-focused class to currently focused textarea element.第 3 步:将last-focused class 添加到当前聚焦的textarea元素。

Step 4: Add click listener on button第 4 步:在button上添加click监听器

Step 5: On button clicked, select last-focused.textarea element, and replace its content with the button's value.第 5 步:在单击button时,select last-focused.textarea focused.textarea 元素,并将其内容替换为按钮的值。

Note: we can use any name for class, just given the name as last-focused , as it relates to the current context.注意:我们可以为 class 使用任何名称,只需将名称命名为last-focused ,因为它与当前上下文相关。

HTML: HTML:

<form>
  <textarea id="text1" cols="40" rows="3"></textarea>
  <textarea id="text2" cols="40" rows="3"></textarea>
  <br>
  <input type="button" value="one" />
  <input type="button" value="two" />
  <input type="button" value="three" />
</form>

JS + JQuery: JS + JQuery:

// Step 1
$('textarea').on('focus', function() {
    // Step 2
    $('textarea.last-focused').removeClass('last-focused');
    // Step 3
    $(this).addClass('last-focused');
});

// Step 4
$('input[type=button]').on('click', function() { 
    // Step 5
    $('textarea.last-focused').html($(this).val());
});

You can track last focused input element with focus event of textarea elements and append last active element's value when button clicked:您可以使用 textarea 元素的焦点事件和 append 单击按钮时最后一个活动元素的值来跟踪最后一个焦点输入元素:

var mostrecent=$('textarea')[0];
$('textarea').each(function(i,item){
  $(item).focus(function(){
    mostrecent=this;
  });
});

 var mostrecent=$('textarea')[0]; $('textarea').each(function(i,item){ $(item).focus(function(){ mostrecent=this; }); }); $( 'input[type=button]' ).on('click', function(){ var cursorPos = $('#text1').prop('selectionStart'); var v = $('#text1').val(); var textBefore = v.substring(0, cursorPos ); var textAfter = v.substring( cursorPos, v.length ); $(mostrecent).val( textBefore+ $(this).val() +textAfter ); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form> <textarea id="text1" cols="40" rows="3"></textarea> <textarea id="text2" cols="40" rows="3"></textarea> <br> <input type="button" value="one" /> <input type="button" value="two" /> <input type="button" value="three" /> </form>

Hook into form events to mark the most recent input as "recent" (using some class) and unmark all other inputs.挂钩表单事件以将最近的输入标记为“最近的”(使用某个类)并取消标记所有其他输入。 On click modify the "recent" input.单击修改“最近”输入。

Most likely you'll need onfocus , but might be onchange depending on your specific use case.您很可能需要onfocus ,但可能会根据您的特定用例进行onchange

The currently selected field is document.activeElement.当前选择的字段是 document.activeElement。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 3个文本框,1个按钮,单击按钮时,将文本放在光标所在的文本框中 - 3 textboxes, 1 button, on button click put text in the textbox where the cursor is Quilljs通过按钮点击光标位置上的图像转到顶部 - Quilljs Insert Image on cursor position via Button click goes to top 如何通过单击按钮将日期和时间插入输入字段 - How can I Insert date and time into input field via a button click 通过Javascript单击按钮时,将文本插入到rich:editor中的光标位置 - Insert text to cursor position in rich:editor when click button by Javascript 如何插入新的<div>在按钮上单击现有的光标位置<div> - How to insert new <div> on a button click at the cursor position of existing <div> 如何使用github api查找最新的存储库? - How can I use github api to find most recent repositories? 如何在 TextBox(用户、密码等)中缩进文本和光标的起始位置 - How can I indent the text, and starting position of cursor, in a TextBox (user, password, etc..) 如何使用 javascript 更新文本框内光标位置处的文本 - How can I use javascript to update text at the cursor location inside a textbox 如果我单击选择按钮并在文本框中传递其值,如何获得所选单选按钮的值? - how can i get the value of selected radio button if i click the select button and pass its value in a textbox? 如何通过按钮单击Ajax获取文本框值 - How to get textbox value via button click Ajax
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM