Kiran
Kiran

Reputation: 1185

How to append characters to selected text in textbox/textarea in JavaScript on key press

I have textbox/textarea input fields by selecting some text inside e.g.

Test Message with sub text and last message

on selecting "Mes" and press ctrl+B it should append <b> (or any character or multiple chars of my choice) to selected text at both ends in JavaScript as shown below

Test <b>Mes<b>sage with sub text and last message

I am able to simulate Ctrl+B key event successfully but not able to replace selected text with new text.

Upvotes: 1

Views: 1078

Answers (2)

Kostya Shkryob
Kostya Shkryob

Reputation: 2369

You can get selection start and end from corresponding fields in textarea.

<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<textarea>Test Message with sub text and last message</textarea>
<script>
jQuery('textarea').on('keydown', function(e) {
	if (e.keyCode == 66 && (e.metaKey || e.ctrlKey)) {
		e.preventDefault();

		var text = jQuery(this).val();
		var start = this.selectionStart;
		var end = this.selectionEnd;
		var selection = '<b>' + text.substring(start, end) + '</b>';
		text = text.substring(0, start) + selection + text.substring(end);
		jQuery(this).val(text);
		this.selectionStart = start;
		this.selectionEnd = start + selection.length;
	}
});
</script>

Upvotes: 1

Alper Cinar
Alper Cinar

Reputation: 861

Following function wraps the selected text in a text area with given string .

I have written an example case

function wrapSelection(textArea, wrappingString) {
    var s = textArea.selectionStart;
    var e = textArea.selectionEnd;
    var oldValue = textArea.value;
    var newValue = oldValue.slice(0, s) + wrappingString + oldValue.slice(s, e) + wrappingString + oldValue.slice(e, oldValue.length);
    textArea.value = newValue;
}

var element = document.getElementById('your-input-element');
element.onselect = function () {
    wrapSelection(element, '<b>');
}

Upvotes: 1

Related Questions