views:

82

answers:

3

Hello,

I need a very simple Javascript on a html page, that will do the following..

Display a text like:

This is a string of text and can be long

then if you mark some of the text with your mouse, the selected text should be inserted and automatically updated into a text field

How can i do it?

+1  A: 

Create readonly textarea (you may use css to decorate it as simple text block). Then process it's onSelect event to precess selection. You will get somethink like:

<script language="JavaScript">
function display(txtarea)
{
    var sl = (txtarea.value).substring(txtarea.selectionStart, txtarea.selectionEnd);  
    alert (sl);
} 
</script>
<textarea name="entry" onSelect="display(this);">Some text.</textarea>
Veton
A: 
<script type="text/javascript">
function render(element)
{
    var stext = element.value.substring(element.selectionStart, element.selectionEnd);  
    document.getElementById('selText').value = stext;
} 
</script>
<input id="selText" value="" />
<textarea name="entry" onclick="render(this);">This is a string of text and can be long
</textarea>

Hope this helps

thephpdeveloper
A: 

Solution with jQuery Based on this link

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){

    var textSelected = function(el, elResult) {

     var len = el.val().length; 
     var textarea = document.getElementById(el.attr("id")); 

     if($.browser.msie) {
      if (document.selection) { 
       var range = document.selection.createRange(); 
       var stored_range = range.duplicate(); 
       stored_range.moveToElementText(textarea); 
       stored_range.setEndPoint('EndToEnd', range); 
       textarea.selectionStart = stored_range.text.length - range.text.length; 
       textarea.selectionEnd = textarea.selectionStart + range.text.length; 

       var start = textarea.selectionStart; 
       var end = textarea.selectionEnd; 
      } 
     } else  { 
      var start = textarea.selectionStart; 
      var end = textarea.selectionEnd;     
     } 

     var sel = textarea.value.substring(start, end); 
     if (sel.length!=0)
      elResult.val(sel);
    };

    $("#text-entry").bind("select", function(){
     textSelected($(this), $("#select-text"));
    });
});
</script>
</head>
<body>
<input id="select-text" type="text" /><br />
<textarea id="text-entry">text for select</textarea>
</body>
</html>
andres descalzo