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.
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:
And my HTML is simply :
So I finally got it. Thanks for everyone’s input!