qw3n
qw3n

Reputation: 6334

How do you insert a special character into a text input at an arbitrary position on button click?

This question has been asked and answered several times for example. However none of them address inserting at an arbitrary point.

So if you have a text input or textarea and a button for some symbol that isn't on the keyboard (e.g. pi) or a button that if text is highlighted you add an accent or some other diacritical mark. How would you insert that at the current caret position or selection? This will not necessarily be at the end if the user moves the cursor and when the mouse is clicked you lose focus on the input which will remove the caret or selection.

<input id="formula" type="text">
<button onclick="insertIntoFormula">π</button>

Upvotes: 0

Views: 2300

Answers (1)

SamVK
SamVK

Reputation: 3405

Sounds like you want .selectionStart (the starting index of the highlighted text) and .selectionEnd (the ending index of the highlighted text). If it's just a cursor, they'll both just return its position.

function insertIntoFormula(specialChar) {
    const textarea = document.getElementById('formula');
    const insertStartPoint = textarea.selectionStart;
    const insertEndPoint = textarea.selectionEnd;
    let value = textarea.value;
 
    // text before cursor/highlighted text + special character + text after cursor/highlighted text
    value = value.slice(0, insertStartPoint) + specialChar + value.slice(insertEndPoint);
    textarea.value = value;
}
<input id="formula" type="text">
<!-- remember to actually pass the special character -->
<!-- (you *could* just get the innerText of the triggering button but I wouldn't recommend it) -->
<button onclick="insertIntoFormula('π')">π</button>
<button onclick="insertIntoFormula('é')">é</button> 

Upvotes: 1

Related Questions