Simtwo Simtwo - 6 months ago 18
jQuery Question

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

I am searching for a way to split a selected word (not all of them, just those who are selected) from an input in character with spaces and uppercase, after clicking a button.
Like this :

before : word

after : W O R D


EDIT : people seems a bit confuse about the problem, so I made an illustration of it 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">




Answer

This is my interpretation of what you've described:

function myFunction() {
    var input = $("input");
    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>

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

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.