Replace selected text from input fields on button click - javascript

I simply try to replace the selected text from an input field e.g from a textarea, with another text.
E.g. if i select a part of the text inside the input field and click the Button CENTER, then the selected text should be wrapped in <center></center>.
I found this "solution" from 2009 which seems to be outdated, I tried it with Chrome and Firefox and I get the info that my browser is not supported.
Is there another way to achieve this? It should work at least with Firefox and Chrome.

Try this:
function getSel() // javascript
{
console.log("test");
// obtain the object reference for the textarea>
var txtarea = document.getElementById("mytextarea");
// obtain the index of the first selected character
var start = txtarea.selectionStart;
// obtain the index of the last selected character
var finish = txtarea.selectionEnd;
//obtain all Text
var allText = txtarea.value;
// obtain the selected text
var sel = allText.substring(start, finish);
//append te text;
var newText=allText.substring(0, start)+"<center>"+sel+"</center>"+allText.substring(finish, allText.length);
console.log(newText);
txtarea.value=newText;
}
https://jsfiddle.net/qpw1eemr/1/

Here is one simple example
$(function() {
$('textarea').select(function(event) {
var elem = $(this);
var start = elem.prop("selectionStart");
var end = elem.prop("selectionEnd");
var prefixStr = elem.text().substring(0, start);
var sufixStr = elem.text().substring(end, elem.text().length);
var selectedStr = elem.text().substring(start, end);
function transform(str) {
return '<center>' + str + '</center>'
}
elem.text(prefixStr + transform(selectedStr) + sufixStr);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea>iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii</textarea>

// hope this would be usefull
// i used these codes for auto completing the texts in textarea.
// other methods change all matching items before the selected text
// but this affects only the text where caret on.
// at first, i divided textarea.value into 3 pieces. these are ;
// p1; until the 'searched' item, p2 after 'searched' item
// and pa = new item that will replaced with 'searched' item
// then, i combined them together again.
var tea = document.getElementById(targetTextArea);
caretPosition = tea.selectionStart - ara.length; //ara=searched item
p1 = tea.value.substring(0,caretPosition);
console.log('p1 text : ' + p1);
p2 = tea.value.substring(caretPosition+ara.length,tea.value.length);
console.log('p2 text : ' + p2);
pa = yeni; //new item
console.log('pa text : ' + pa);
tea.value = p1 + pa + p2;
tea.selectionStart = caretPosition + yeni.length;
tea.selectionEnd = caretPosition + yeni.length;
tea.focus();

Related

How to find index of selected text in getSelection() using javascript?

I am trying to apply style to the text selected by the user(mouse drag) for which I need to get the start and end index of the selected text.
I have tried using "indexOf(...)" method. but it returns the first occurrence of the selected substring. I want the actual position of the substring with respect to the original string. For example.., if I select the letter 'O' at position 3 [YOLO Cobe], I expect the index as 3 but the indexOf() method returns 1 which is the first occurrence of 'O' in [YOLO Cobe].
Is there any other method of getting the actual start and end index of selected text and not the first occurrence ?
function getSelectionText()
{
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
}
return text;
}
document.getElementById('ip').addEventListener('mouseup',function(e)
{
var txt=this.innerText;
console.log(txt);
var selectedText = getSelectionText();
console.log(selectedText);
var start = txt.indexOf(selectedText);
var end = start + selectedText.length;
if (start >= 0 && end >= 0){
console.log("start: " + start);
console.log("end: " + end);
}
});
<div id="ip">YOLO Cobe</div>
What you are looking for is available inside object returned by window.getSelection()
document.getElementById('ip').addEventListener('mouseup',function(e)
{
var txt = this.innerText;
var selection = window.getSelection();
var start = selection.anchorOffset;
var end = selection.focusOffset;
if (start >= 0 && end >= 0){
console.log("start: " + start);
console.log("end: " + end);
}
});
<div id="ip">YOLO Cobe</div>
And here is example for more complex selections on page based on #Kaiido comment:
document.addEventListener('mouseup',function(e)
{
var txt = this.innerText;
var selection = window.getSelection();
var start = selection.anchorOffset;
var end = selection.focusOffset;
console.log('start at postion', start, 'in node', selection.anchorNode.wholeText)
console.log('stop at position', end, 'in node', selection.focusNode.wholeText)
});
<div><span>Fragment1</span> fragment2 <span>fragment3</span></div>
window.getSelection().anchorOffset will give you the index that you are looking for.
MDN link: https://developer.mozilla.org/en-US/docs/Web/API/Selection/anchorOffset
I tried using the anchorOffset and focusOffset from the getSelection() method and it wasn't giving me the desired index.
So I came up with this solution myself (Note: it worked in chrome, don't know about other browsers)
HTML
<input type="text" class="input" hidden />
<textarea> remind me to be here to morrow </textarea>
JS
let text = document.querySelector("textarea");
let input = document.querySelector(".input");
In this instance, "here to morrow" is the highlighted portion.
For the selected text I did
input.value = getSelection();
let selectedText = input.value;
For the starting index of the selected text, I did
let start = body.value.indexOf(getSelection());
let end = start + selectedText.lenght;
Hope this proves useful

how to make space must be remains same after replacing text?

I have text, in which on selection I need to replace the text.
Here my requirement is, the space must be remain same after replacing the characters which contains spaces between them.
JavaScript:
function getSel() {
// obtain the object reference for the textarea>
var txtarea = document.getElementById("mytextarea");
// obtain the index of the first selected character
var start = txtarea.selectionStart;
// obtain the index of the last selected character
var finish = txtarea.selectionEnd;
//obtain all Text
var allText = txtarea.value;
// obtain the selected text
var sel = Array(finish - start).join("*");
//append te text;
var newText = allText.substring(0, start) + sel + allText.substring(finish, allText.length);
txtarea.value = newText;
$('#newpost').offset({ top: 0, left: 0 }).hide();
}
$(document).ready(function () {
var position;
$('#newpost').hide();
$('#mytextarea').on('select', function (e) {
$('#newpost').offset(position).show();
var txtarea = document.getElementById("mytextarea");
var start = txtarea.selectionStart;
var finish = txtarea.selectionEnd;
$('#newpost p').text(Array(finish - start).join("*"));
}).on('mousedown', function (e) {
position = { top: e.pageY-5, left: e.pageX};
});
$('#newpost').hide();
});
Here is my plunker
I am getting output as shown in above image but in expected output the space must not be replaced with asterisk .
Use string.replace instead, try this:
console.log('g2ggg gggGG'.replace(/[a-zA-Z0-9]/g, '*'))
Your all string manipulation logic will be only 1 line:
newText = allText.replace(/[a-zA-Z0-9]/g, '*')
I'm not very good at regex so I used a for-loop but maybe this still helps you.
$(document).ready(function () {
$('#mytextarea').on('select', function (e) {
var $output = $("#output");
var $txtarea = $("#mytextarea");
var start = $txtarea[0].selectionStart;
var finish = $txtarea[0].selectionEnd;
var subtext = $txtarea.text().substr(start, finish);
var out = "";
for (var i = 0; i < subtext.length; i++) {
var char = subtext[i];
if (char == " ") {
out += " ";
} else {
out += "*";
}
}
$output.text(out);
});
});
Based on your code you can see the working example in this fiddle:

selectionStart and selectionEnd for textarea/input not working properly in java script

i want to get the cursor position's value where started focus to end
for this am using
var doIt = function() {
var elem = document.getElementById("mytext");
var start = elem.selectionStart;
var end = elem.selectionEnd;
var selection = elem.selection;
alert("selectionStart: " + start
+ "\nselectionEnd :" + end
+ "\nselection: " + selection);
}
but problem is selectionStart and selectionEnd getting same last value only. how to get properly start and end value
example is here http://jsfiddle.net/5vd8pxct/ which i tried
I've modified your code for your desired results. Here boolean firstKeyup keeps track of first keyup event at first load and after clicking the button.
var elem = document.getElementById("mytext");
var start = 0;
var firstKeyup = true;
elem.addEventListener('keyup', function() {
if(firstKeyup) {
start = elem.selectionStart;
firstKeyup = false;
}
});
function doIt() {
var end = elem.selectionEnd;
var selection = elem.selection;
alert("selectionStart: " + start
+ "\nselectionEnd :" + end
+ "\nselection: " + selection);
firstKeyup = true;
}
<textarea id="mytext" rows="10" cols="30">
Really long text goes here
</textarea><br/>
<button onclick="doIt();">Click Me</button>

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.
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>
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>');
}

Context menu JavaScript can not get the selected text if the text is a input tag / textbox

I had a very big problem, to get somehow the selected text from the webpage then process it using a contextmenu... when I solved for Chrome, Firefox, and IE11, I found I can't get the selected text in Firefox and Internet Explorer when the selected text is in a Input box....
I have searched for days to solve somehow, and finally I had success...
This was the original script for Internet Explorer
var parentwin = external.menuArguments
var selectedText = getSel();
function getSel(){
var w=window,d=parentwin.document,gS='getSelection';
return (''+(w[gS]?w[gS]():d[gS]?d[gS]():d.selection.createRange().text)).replace(/(^\s+|\s+$)/g,'');
}
And this for FireFox
var contextMenu = require("sdk/context-menu");
var tabs = require("sdk/tabs");
var clipboard = require("sdk/clipboard");
var {Cc,Ci} = require('chrome');
var simpleGetLibrary = null;
var menuItem = contextMenu.Item({
label: "Get selected text",
context: contextMenu.SelectionContext(),
contentScript: 'self.on("click", function () {' +
' var text = window.getSelection().toString();' +
' self.postMessage(text);' +
'});',
onMessage: function (selectionText) {
console.log(selectionText);
clipboard.set(selectionText); //this line copy the selected text to Clipboard
}
But I had no idea, how I can solve to get somehow the text when it is in a input box... <INPUT> ...</INPUT>
The solution is the following...
For Internet Explorer IE11
var parentwin = external.menuArguments
var selectedText = getSel();
function getSel(){
var w=parentwin.window,d=parentwin.document,gS='getSelection';
var selectedText;
var rv=(''+(w[gS]?w[gS]():d[gS]?d[gS]():d.selection.createRange().text)).replace(/(^\s+|\s+$)/g,'');
parentwin.console.log("the selected text is in first try is:"+rv);
if (rv=="") {
var allinput = parentwin.document.getElementsByTagName("input"); //I get an array of all input tags
var index;
var newsel;
var found="false";
for (index = 0; index < allinput.length; index++) {
parentwin.console.log("index: "+index);
newsel="";
parentwin.console.log("newsel= ");
try {
var ss = allinput[index].selectionStart;
parentwin.console.log("ss");
var se = allinput[index].selectionEnd;
parentwin.console.log("se");
if (typeof ss === "number" && typeof se === "number") {
newsel=allinput[index].value.substring(ss, se);
found=newsel;
if (newsel.length>0){
rv=newsel;
found="true";
allinput[index].selectionEnd=allinput[index].selectionStart;
newsel="";
}
}
}
catch(err){}
parentwin.console.log("input fields "+index+"/"+allinput.length+" fieldname:"+allinput[index].getAttribute("name")+" selection: "+newsel);
if (found=="true"){
index=allinput.length;
}
}
parentwin.console.log("found=:"+found);
}
return rv;
}
And for Firefox is a little bit tricky, because I can't have access to the DOM so I need to resolve this in ContentScript building and then I send directly the result.. because I can't solve how to get only the selection, I send the value of the input box, is don't matter if is not all selected...
var contextMenu = require("sdk/context-menu");
var tabs = require("sdk/tabs");
var clipboard = require("sdk/clipboard");
var preferences = require("sdk/simple-prefs").prefs;
var {Cc,Ci} = require('chrome');
var simpleGetLibrary = null;
var menuItem = contextMenu.Item({
label: "Get selected text",
context: contextMenu.SelectionContext(),
contentScript: 'self.on("click", function (node, data) {' +
' var text = window.getSelection().toString();' +
' console.log("Selected node is: "+node.nodeName);' +
' console.log("Selected value is: "+node.value);' +
' if (text.lenght>0)' +
' self.postMessage(text);' +
' else ' +
' if (node.nodeName=="INPUT")' +
' self.postMessage(node.value);' +
'});',
onMessage: function (selectionText) {
console.log("Selection sent for processing is: "+selectionText);
clipboard.set(selectionText); //this line copy the selected text to Clipboard
}

Categories

Resources