Gabriel
Gabriel

Reputation: 2750

Can I retrieve the user selected text in a text form input?

I'm trying to get only the selected part of an input string that was selected by the user. Let's say I have this input :

<input type="text" name="first_name" id="first_name" value="Enter your name" />

And the user selects the "Enter" word by clicking and dragging in the text field. Can I retrieve that text with jQuery?

I know I can get the whole value this way :

$("#first_name").val();

But so far, I didn't find anyway to get only the selected "Enter" part. Anyone is able to point me in the right direction? Thanks!

EDIT

I tried document.getSelection and it's working great in Firefox on a static text element such as a "p". It's not working for me so far on a text input.

In IE, window.selection.createRange().text is working both on a "p" and in a text input.

Upvotes: 7

Views: 934

Answers (4)

Gabriel
Gabriel

Reputation: 2750

Ok here's the final answer. Looks like we have to use selectionStart and selectionEnd instead of getSelection() when we're working with input or textarea. Here's my test code:

$(".name").mouseup(function()
{
    var selected_text = "";
    if (window.getSelection) // Firefox
    {
        var text = $(this).val();
        selected_text = text.substring(document.activeElement.selectionStart, document.activeElement.selectionEnd);
    }
    else // IE
    {
        selected_text = document.selection.createRange().text;
    }
    alert(selected_text);
});

And my HTML is simply :

<input type="text" name="name" class="name" value="Enter your name" />

So I finally got it. Thanks for everyone's input!

Upvotes: 1

sgriffinusa
sgriffinusa

Reputation: 4221

You could use the regular javascript replace method.

$("#first_name").val().replace("Enter your name", "")

See an example: http://jsfiddle.net/gezDF/

However, another option could be to remove the text when the user entered the field. This can be done with something like the following:

$(document).ready(function(){
    $("#first_name").focus(function () {
         $(this).val("");
    });
}​);​

See an example: http://jsfiddle.net/JNmAF/

Upvotes: 1

heisenberg
heisenberg

Reputation: 9759

Should be able to do this using jQuery's select function and document.getSelection

http://www.devguru.com/Technologies/ecmascript/quickref/doc_getselection.html http://api.jquery.com/select/

Upvotes: 3

Pablo Santa Cruz
Pablo Santa Cruz

Reputation: 181430

This might help. You will need to use .select() function.

Upvotes: 2

Related Questions