I have a label on my page and want to select the text of this label whenever user click on it so it will be easier for user to Ctrl+C text on this label.
I tried using SomeLabel.Attributes["onclick"] = "javascript:this.select();"; but it didn't work.
Is there any way to do this?
Try this:
function fnSelect(objId) {
if (document.selection) {
var range = document.body.createTextRange();
range.moveToElementText(document.getElementById(objId));
range.select();
}
else if (window.getSelection) {
var range = document.createRange();
range.selectNode(document.getElementById(objId));
window.getSelection().addRange(range);
}
}
SomeLabel.Attributes["onclick"] = "javascript:fnSelect(" + SomeLabel.ClientID + ");";
Try This one
SomeLabel.Attributes.Add("onclick","javascript:fnSelect('" + SomeLabel.ClientID + "');");
Related
i am trying to wrap the selected string between two characters
for eg: selecting 'test' and clicking on change button will change the selected text to 'atestb'
the problem is that, i am able to replace the selected text, but window.getSelection().toString() is coming empty.
This is the function that im using
replaceSelectedText(startTag, endTag) {
let sel, range;
console.log(window.getSelection().toString())
if (window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
const selectedContent = sel.toString();
console.log("Selected Content ")
console.log(selectedContent)
let replaceDiv = startTag + selectedContent;
replaceDiv=endTag ? replaceDiv + endTag : replaceDiv;
range.insertNode(document.createTextNode(replaceDiv));
}
} else if ((document as any).selection && (document as any).selection.createRange) {
range = (document as any).selection.createRange();
range.text = startTag;
}
}
Link to Stackblitz
https://stackblitz.com/edit/angular-idyhj5?file=src%2Fapp%2Fapp.component.ts
You are deleting the value before retrieving it.
range.deleteContents();
const selectedContent = sel.toString();
If you flip those two lines and store the contents before deleting, it will work as you expect.
I am designing an chrome extension for Gmail. In this I want to get selected/highlighted text. I tried following code:
if (!window.x) {
x = {};
}
x.Selector = {};
x.Selector.getSelected = function() {
var t = '';
if($('.compose-container').getSelection){
t = $('.compose-container').getSelection();
alert(t);
} else if (window.getSelection) {
t = window.getSelection();
} else if (document.getSelection) {
t = document.getSelection();
} else if (document.selection) {
t = document.selection.createRange().text;
}
return t;
}
It is not giving me selected text in compose mail.
Please help me out.
You would need to use the copy command to achieve this.
var copyText = document.execCommand('copy');
Basically it will copy any text selection in the browser.
You can check out this link on how it was fully utilized
As per gRenzFries answer, I code same as link provided by him. But slight addition in code to paste it in textbox.
Code to Copy text :
var emailLink = document.querySelector('.gmail_default');
var range = document.createRange();
range.selectNode(emailLink);
window.getSelection().addRange(range);
try {
// Now that we've selected the anchor text, execute the copy command
var successful = document.execCommand('copy', true);
} catch(err) {
}
Code to paste it in textbox:
$('#text-to-display').val(""); //reset textbox value
$('#text-to-display').focus(); //set focus to textbox
document.execCommand("Paste");
This code works just as expected.
I am working in HTML with jquery.
I want to make a webpage to highlight some text lines (line nos 15, 22, 32) in that page at a time. This can be done by left click in mouse and drag that line, so that the text line is selected with blue background.
I am able to get the selected lines as follows using jquery,
function getText() {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
console.log('text-----------'+text)
}
When I am clicking other line, first selected line was disappears. I need that line also be available. (In MSword, we can hold ctrl and drag the lines and it will be available)
For multiple selection, I know there is more plugins available in web. But I am looking for doing this selection using Javascript or jquery.
This is what I am looking for to do in my page, want to select texts and get them in my javascript function.
How may we do this?
This answer is combined of some issues.
Get the selection text
Mark it.
Copy to clipboard
It's not the full solution but there are all the parts.
So:
var output = '';
$('#test').mouseup(function () {
output += getSelectedText();
highlightSelected();
copyOutput();
$('#result').html(output);
});
function getSelectedText() {
if (window.getSelection) {
return window.getSelection().toString();
} else if (document.selection) {
return document.selection.createRange().text;
}
return '';
}
function highlightSelected() {
var SelRange;
if (window.getSelection) {
SelRange = window.getSelection().getRangeAt(0);
} else if (document.getSelection) {
SelRange = document.getSelection().getRangeAt(0);
} else if (document.selection) {
SelRange = document.selection.createRange();
}
if (SelRange.pasteHTML) {
SelRange.pasteHTML('<span class="hilited1">' + SelRange.text + '</span>');
}
else {
var newNode = $('<span class="hilited1" />')[0];
SelRange.surroundContents(newNode);
}
}
function copyOutput() {
var emailLink = document.querySelector('#result');
var range = document.createRange();
range.selectNode(emailLink);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
try {
var successful = document.execCommand('copy');
} catch (err) {
console.log('Oops, unable to copy');
}
window.getSelection().removeAllRanges();
}
textarea {
width:100%;
height:150px;
}
.hilited1 {
background:red;
color:#fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">I am working in HTML with jquery.
I want to make a webpage to highlight some text lines (line nos 15, 22, 32) in that page at a time. This can be done by left click in mouse and drag that line, so that the text line is selected with blue background.
I am able to get the selected lines as follows using jquery,
</div>
<hr />
<div id="result"></div>
<hr />
<textarea placeholder="Try to paste here"></textarea>
I found the following code online which works well. I would like to use this on multiple elements on the same page and do not know how to do this. I can get the first to work but not the second.
Can anyone help?
Thanks,
John
Javascript:
function SelectText(element) {
var doc = document
, text = doc.getElementById(element)
, range, selection
;
if (doc.body.createTextRange) {
range = document.body.createTextRange();
range.moveToElementText(text);
range.select();
} else if (window.getSelection) {
selection = window.getSelection();
range = document.createRange();
range.selectNodeContents(text);
selection.removeAllRanges();
selection.addRange(range);
}
}
document.onclick = function(e) {
if (e.target.className === 'select') {
SelectText('some_text');
}
};
HTML:
<span id ='some_text'>Text to select </span><span class='select'>select</span>
<span id ='more_text'>More text to select</span><span class='select'>select</span>
Because you call function with same parameter.
SelectText('some_text');
"Text to select" will be selected no matter what class="select" you click.
Try this code:
function SelectText(element) {
var doc = document
, text = doc.getElementById(element)
, range, selection;
if (doc.body.createTextRange) {
range = document.body.createTextRange();
range.moveToElementText(text);
range.select();
} else if (window.getSelection) {
selection = window.getSelection();
range = document.createRange();
range.selectNodeContents(text);
selection.removeAllRanges();
selection.addRange(range);
}
}
document.onclick = function(e) {
if (e.target.className === 'select') {
SelectText(e.target.getAttribute('data-id'));
}
};
And change the HTML:
<span id ='some_text'>Text to select </span><span class='select' data-id="some_text">select</span>
<span id ='more_text'>More text to select</span><span class='select' data-id="more_text">select</span>
You can give a special attribute to each span with the id of the element you want to select:
//JS
SelectText(e.target.attributes["select"].value);
//HTML
<span class='select' select="some_text">select</span>
<span class='select' select="more_text">select</span>
Or, if the order of the elements is always similar and is not likely to change, you can retrieve the previous sibling:
SelectText(e.target.previousSibling.id);
For your case you can do:
SelectText(e.target.previousSibling.id);
I know how to set an <a /> tag with the href attribute in a contenteditable like this:
execCommand("CreateLink", false, "#jumpmark");
which will result in
selection
However I cannot figure out how to set an anchor name instead of the href.
This is my desired result:
<a name="jumpmark">selection</a>
Can anyone help me?
Side notes: I am using jQuery and Rangy as libraries, however I would prefer a solution that works directly with execCommand.
Update: Here's a jsfiddle: http://jsfiddle.net/fjYHr/ Select some text and click the button. All I want is that with the button click a link is inserted with a name attribute set instead of the href.
You could use something like the following, which is adapted from the pasteHtmlAtCaret() function from this answer of mine:
Demo: http://jsfiddle.net/F8Zny/
Code:
function surroundSelectedText(element) {
var sel, range;
if (window.getSelection) {
// IE9 and non-IE
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
element.appendChild( document.createTextNode(range.toString()) );
range.deleteContents();
range.insertNode(element);
// Preserve the selection
range = range.cloneRange();
range.setStartAfter(element);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
} else if (document.selection && document.selection.type != "Control") {
// IE < 9
var selRange = document.selection.createRange();
element.appendChild( document.createTextNode(selRange.text) );
selRange.pasteHTML(element.outerHTML);
}
}
If you must use document.execCommand() then you could use the InsertHTML command in non-IE browsers. However, IE does not support it.
document.execCommand("InsertHTML", false, '<a name="jumpmark">selection</a>');
I see you're using Rangy, but I don't how to use it at all. Before I realized what Rangy was, I looked up how to get the current selection. I found a function that gets it and replaces it with a passed in value. I ended up modfiying it, but here it is:
http://jsfiddle.net/fjYHr/1/
$(document).ready(function () {
$("#setlink").click(function () {
replaceSelectedText("jumplink");
});
});
function replaceSelectedText(nameValue) {
var sel, sel2, range;
if (window.getSelection) {
sel = window.getSelection();
sel2 = ""+sel; // Copy selection value
if (sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
var newA = document.createElement("a");
newA.name = nameValue;
newA.innerHTML = sel2;
range.insertNode(newA);
}
} else if (document.selection && document.selection.createRange) {
// Not sure what to do here
range = document.selection.createRange();
var newA = "<a name='" + nameValue.replace(/'/g, "") + "'>" + range.text + "</a>";
range.text = newA;
}
}
Notice how I store the original current selection, then replace it with an <a> element that gets its name set with the passed-in value.
As for the document.selection part (which seems to be used by IE < 9), I'm not 100% sure that the code I provided will work (actually allow HTML in the selection, and not escaping it). But it's my attempt :)
As you've seen execCommand is rather limited in the attributes you can set, as such you cannot set the name attribute using it - only the href.
As you have jQuery set as a tag, you can use that as an alternative:
var $a = $('<a></a>').attr('name', 'jumpmark').appendTo('body');
Update
I need to work on the current selection. Specifically I don't have a jQuery object that I can append to, meaning I don't have a DOM node that I can work on
In this case use a plugin such as Rangy to get the selection which you can then amend with jQuery as required.