Yagayente
Yagayente

Reputation: 341

Split a selected word(s) in characters and add spaces

I am searching for a way to split and uppercase the currently selected text in an input field. I only want the selected text, not the entire value of the field. After clicking a button, I want to have that selected text be split into individual characters, separated by spaces, and upper-cased.

Here is an example:

before: word

after: W O R D

Here is a graphical illustration of what I'm trying to achieve: Because am image worth a thousand words

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<button onclick="myFunction()">Click me</button><br>

<input type="text" value="Write here">

Upvotes: 0

Views: 120

Answers (2)

Michael Gaskill
Michael Gaskill

Reputation: 8042

This is my interpretation of what you've described:

function myFunction() {
    var input = $("textarea");
    var istart = input[0].selectionStart;
    var iend = input[0].selectionEnd;
    var val = input.val();
    var seltext = val.substr(istart, iend-istart).split("").join(" ");
    var newval = val.substring(0, istart) + seltext.toUpperCase() + val.substring(iend, val.length);
    input.val(newval);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<button onclick="myFunction()">Click me</button><br>

<textarea>Write here</textarea>

I have removed the handler for the select event on the input, and left the click event on the button as the initiator to split the selection.

Upvotes: 2

Moritz
Moritz

Reputation: 471

I made a little jsfiddle: https://jsfiddle.net/20rmguhu/
The Code should be pretty much self explaining. Just ask if it isn't. You don't really need jQuery for this, but if you want you can replace the querySelector and addEventListener with jQuery functions.

html:

<input id="myInput" value="Write here">
<button>Click me</button>

Js:

var button = document.querySelector("button");

button.addEventListener("click", function () {
    var myInput = document.querySelector("#myInput");

    var text = myInput.value;
    var selectionStart = myInput.selectionStart;
    var selectionEnd = myInput.selectionEnd;

    var selectedText = text.substr(selectionStart, selectionEnd);
    var textBefore = text.substr(0, selectionStart);
    var textAfter = text.substr(selectionEnd);

    // make the text uppercase and add spaces between each letter
    selectedText = selectedText.toUpperCase().split("").join(" ");
    myInput.value = textBefore + selectedText + textAfter;

    // select the changed text again
    myInput.setSelectionRange(selectionStart, selectionStart + selectedText.length);
});

Upvotes: 1

Related Questions