Question

I fail to capitalize selected text in textareas via onClick.

After hours of googling I fopund out there is no built in method to get the select text in texareas.

I found Replacing selected text in the textarea which replaces text.

How could it be adjusted capitalize the selected text?

Testing: http://jsfiddle.net/tDYe4/2/

Was it helpful?

Solution

Here's a modified version of your function that works. Updated your fiddle.

function capitalizeSelectedText(el) {
    var sel       = getInputSelection(el),
        val       = el.value,
        selection = val.substring(sel.start, sel.end);

    if(!selection) return;

    var new_text = val.substring(0, sel.start) + selection.toUpperCase() + val.substring(sel.end);
    el.value = new_text;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top