Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there a javascript/jquery selector for text selected by mouse cursor?

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.

like image 296
user701510 Avatar asked Oct 01 '11 06:10

user701510


2 Answers

There'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);
like image 83
Chazbot Avatar answered Sep 30 '22 06:09

Chazbot


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 =)

like image 27
Stian Olsen Avatar answered Sep 30 '22 06:09

Stian Olsen