Add text on that field where cursor is with jquery

Viewed 48

There are two fields, subject and description and I want to add text where the cursor is. It means, if cursor is on description, it should add text in description and if cursor is on subject, it should add text on subject field.

one field is #subject other one is #description

How I can achieve it?

<button type="button" class="btn btn-light mb-1" onclick="insertText('ticket_id')">Ticket ID</button>

 function insertText(text)
{
   // here will be code
}

inputs

<textarea class="form-control form-control-solid" rows="4" id="description" name="description" placeholder="Description"></textarea>

<input type="text" class="form-control form-control-solid" placeholder="Subject" name="subject" value="" />
1 Answers

There is a document.activeElement property, which contains currently focused element, but this will already be changed when click event occurs, so you'll need to use mousedown event, which happens before the focus changes to the button.

Then, element.selectionStart can be used to determine the cursor location. If you also need to replace selected text in the input you should use this in combination with element.selectionEnd and modify the click handler accordingly.

Here is an example:

ticketIdButton = document.getElementById('ticketIdButton')
ticketIdInput = null
ticketIdInputCursorLocation = 0

// In mousedown event document.activeElement has not changed yet
// which allows to keep track of previously focused input
ticketIdButton.addEventListener('mousedown', function() {
  activeElement = document.activeElement
  // For simplicity, let's use ticketIdInput class to identify
  // the acceptable inputs for ticket id
  if (activeElement.classList.contains('ticketIdInput')) {
    ticketIdInput = activeElement
    ticketIdInputCursorLocation = activeElement.selectionStart
  }
  else {
    ticketIdInput = null
  }
})

ticketIdButton.addEventListener('click', function() {
  ticketId = '#1234'
  if (ticketIdInput !== null) {
    ticketIdInput.value = ticketIdInput.value.substring(0, ticketIdInputCursorLocation) + ticketId + ticketIdInput.value.substring(ticketIdInputCursorLocation)
  }
})
<textarea id="description" class="ticketIdInput" placeholder="Description"></textarea><br />
<input id="subject" class="ticketIdInput" placeholder="Subject"><br />
<hr>
<button type="button" id="ticketIdButton">Ticket ID</button>

Related