Reputation: 141
Is there a way in which I can get the selected text in a table using jquery after _mouseStop?
<table id='grid' class='TableStyle'>
<tr>
<td class='cellGrid'>F</td>
<td class='cellGrid'>W</td>
</tr>
<tr>
<td class='cellGrid'>F</td>
<td class='cellGrid'>W</td>
</tr>
</table>
When the text is highlighted, the class of that td
, is changed to cellHighlight
.
I think that I need to loop in the table grid and find those that their class is cellHighlight
and then use .text()
to get the value?
Am I right? If yes, is there a way to do this?
Thanks
Upvotes: 0
Views: 770
Reputation: 400
$("#grid .cellGrid").mouseup( function(){
alert($(this).html());
});
Upvotes: 0
Reputation: 74738
I have found something interesting just what you want, may be something like this:
function getSelectionHtml() {
var html = "";
if (typeof window.getSelection != "undefined") {
var sel = window.getSelection();
if (sel.rangeCount) {
var container = document.createElement("div");
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
container.appendChild(sel.getRangeAt(i).cloneContents());
}
html = container.innerHTML;
}
} else if (typeof document.selection != "undefined") {
if (document.selection.type == "Text") {
html = document.selection.createRange().htmlText;
}
}
alert(html);
}
This is answered by Alison on this post How to get selected(user-highlighted) text in contenteditable element and replace it?
Upvotes: 0
Reputation: 47172
If there's only one (1) that can be highlighted at a time then you can do
var hightlightedText = $('table#grid td.cellHighlight').text();
console.log(hightlightedText);
However if you have multiple cases:
var cells = $('#grid .cellHighlight');
var texts = []
$.each(cells, function(index){
texts.push($(cells[index]).text());
});
console.log(texts);
>> ["W", "F"]
An example JsFiddle found here
Upvotes: 2
Reputation: 12375
If all that you wanted was to get the selectedText anywhere on your page. you should do this.
function getSelectionText() {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
alert( text);
}
see this fiddle
Upvotes: 0