Googlebot
Googlebot

Reputation: 15683

How to select text with jQuery

How can I select a part of the text and process by jQuery? For example, I have a text as

<div id="test">This is an example text here</div>

I select few words (not the whole div) with mouse, and want to show these words (part of #test) in

<div id="target"></div>

Upvotes: 5

Views: 3066

Answers (6)

Tim Down
Tim Down

Reputation: 324657

Here's how. The following works in all major browsers, including IE 6.

function getSelectedText() {
    var selectedText = "", sel;
    if (window.getSelection) {
        selectedText = "" + window.getSelection();
    } else if ( (sel = document.selection) && sel.type == "Text") {
        selectedText = sel.createRange().text;
    }
    return selectedText;
}

$('#target').text( getSelectedText() );

Upvotes: 2

Ravi Vanapalli
Ravi Vanapalli

Reputation: 9952

You would have to use http://www.examplet.buss.hk/jquery/caret.php plugin and you could easily get the selected text

// Get start pos in intput box with id="box1" $("#box1").caret().start

// Get end pos $("#box1").caret().end

// Get selected text $("#box1").caret().text

Upvotes: 1

Rich O&#39;Kelly
Rich O&#39;Kelly

Reputation: 41767

You can use the text method like so:

(function(namespace) {
  namespace.getSelected = function() {
    var t = '';
    if (window.getSelection) {
        t = window.getSelection();
    } else if (document.getSelection) {
        t = document.getSelection();
    } else if (document.selection) {
        t = document.selection.createRange().text;
    }
    return t;
  };
}(Namespace || {}))

$(function() {
  $('#test').on("mouseup", function() {
    var selectedText = Namespace.getSelected();
    if (selectedText) {
      $('#target').text(selectedText);
    }
  });
});

Upvotes: 3

nkm
nkm

Reputation: 5914

$.fn.selectRange = function(start, end) {
    return this.each(function() {
        if(this.setSelectionRange) {
            this.focus();
            this.setSelectionRange(start, end);
        } else if(this.createTextRange) {
            var range = this.createTextRange();
            range.collapse(true);
            range.moveEnd('character', end);
            range.moveStart('character', start);
            range.select();
        }
    });
};

Reference: http://programanddesign.com/js/jquery-select-text-range/

Upvotes: 1

MacMac
MacMac

Reputation: 35351

If you mean by select text then show it into an element.

var selectedText;

if(window.getSelection)
{
    selectedText = window.getSelection();
}
else if(document.getSelection)
{
    selectedText = document.getSelection();
}
else if(document.selection)
{
    selectedText = document.selection.createRange();
}

$('#target').text(selectedText.toString());

Or by typical showing an element text into another element, then you use:

$('#target').text($('#test').text());

Upvotes: 6

Related Questions