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.
We can get the value of the text input field using various methods in JavaScript. There is a text value property that can set and return the value of the value attribute of a text field. Also, we can use the jquery val() method inside the script to get or set the value of the text input field.
To extract the information which a user enters into the text fields using Javascript, the Javascript code to do would be: The line document. getElementById("firstname"). value accesses the text box with an id of firstname and retrieves the value which the user has entered into this text box.
To select text, click and drag your cursor across the text. The text that is highlighted in gray is selected text. Selected text can be copied, cut, or pasted. Many features and settings in Microsoft Office are applied only to text that is selected.
<input>: The Input (Form Input) element. The <input> HTML element is used to create interactive controls for web-based forms in order to accept data from the user; a wide variety of types of input data and control widgets are available, depending on the device and user agent.
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/
This might help. You will need to use .select()
function.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With