is there a jquery selector for text that is highlighted after its dragged over by the mouse cursor? For example, I want to select text that I've typed into my textarea
field, click a button, which puts <p>
tags around the text I've highlighted with my mouse cursor. A non-plugin solution would be preferred, thanks.
is there a jquery selector for text that is highlighted after its dragged over by the mouse cursor? For example, I want to select text that I've typed into my textarea
field, click a button, which puts <p>
tags around the text I've highlighted with my mouse cursor. A non-plugin solution would be preferred, thanks.
- you want that selected text should be highlighted!! m i getting u right?? – xkeshav Commented Oct 1, 2011 at 6:30
- 1 There isn't simply a jQuery selector for selected text, you'll need to bind an event handler and jump through a few JavaScript hoops to get to the selection and modify the textarea. – BoltClock Commented Oct 1, 2011 at 6:52
- 2 mark.koli.ch/2009/09/… – Vicente Plata Commented Oct 1, 2011 at 6:53
2 Answers
Reset to default 5There's a straight up javascript solution that's pretty nice... just use inputElement.selectionStart
and inputElement.selectionEnd
.
It's helpful to note that this is just on Dom elements, so you'll have to take your jQuery selector for your textarea and add [0] to get the element itself, ie. $("#myTextArea")[0].selectionStart
.
From there you can do some string work and add in your <p>
tags at the appropriate indexes.
I haven't tested this, but it should work...
var selStart = $("#myTextArea")[0].selectionStart;
var selEnd = $("#myTextArea")[0].selectionEnd;
var originalString = $("#myTextArea").val();
var segment_1 = originalString.substr(0,selStart);
var segment_2 = originalString.substr(selStart,selEnd);
var segment_3 = originalString.substr(selEnd,originalString.length);
var finalString = segment_1 + "<p>" + segment_2 + "</p>" + segment_3;
$("#myTextArea").val(finalString);
Why dont you use php for this? PHP + jQuery will help you.
Example form:
<form action="highlight.php" method="post">
My textarea:<br />
<textarea cols="10" rows="10" name="textarea"></textarea>
<input type="submit" value="Wrap <p> around" />
</form>
PHP to process the form and wrap
around it:
<?php
$text = $_POST[''];
$wrap = '<p>'.$text.'</p>';
echo '<textarea cols="10" rows="10">'.$wrap.'</p>';
?>
You can remove echo $wrap, but i prefer you learn jQuery and how you can use it to execute a php script.
I Dont have that much jQuery experience to tell you how, but learn it or google "How to execute php script with jquery" and im sure you will find something =)