views:

22

answers:

1

In a text area how to insert the pattern name next to the cursor position using jQuery and after which the cursor should be after the pattern:This should happen on the button click

     <input type="button" value="insert pattern" >
     <textarea rows="10" id="comments">INSERT The condition</textarea>
+1  A: 

Please see this answer. That's where I got the insertAtCaret() method. I went ahead and hooked it up to your button...not sure exactly what you mean by "the pattern name." Is that a SQL thing? Is it based on some previous input field in HTML? Hard to help any further than this without more detail.

function insertAtCaret(areaId,text) {
    var txtarea = document.getElementById(areaId);
    var scrollPos = txtarea.scrollTop;
    var strPos = 0;
    var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ? 
        "ff" : (document.selection ? "ie" : false ) );
    if (br == "ie") { 
        txtarea.focus();
        var range = document.selection.createRange();
        range.moveStart ('character', -txtarea.value.length);
        strPos = range.text.length;
    }
    else if (br == "ff") strPos = txtarea.selectionStart;

    var front = (txtarea.value).substring(0,strPos);  
    var back = (txtarea.value).substring(strPos,txtarea.value.length); 
    txtarea.value=front+text+back;
    strPos = strPos + text.length;
    if (br == "ie") { 
        txtarea.focus();
        var range = document.selection.createRange();
        range.moveStart ('character', -txtarea.value.length);
        range.moveStart ('character', strPos);
        range.moveEnd ('character', 0);
        range.select();
    }
    else if (br == "ff") {
        txtarea.selectionStart = strPos;
        txtarea.selectionEnd = strPos;
        txtarea.focus();
    }
    txtarea.scrollTop = scrollPos;
}


$(document).ready(function(){
  $("#insertPattern").click(function(){
    insertAtCaret("comments","name");
  });
});​

Then, in your HTML:

  <input id="insertPattern" type="button" value="insert pattern" />
  <textarea rows="10" id="comments">INSERT The condition</textarea>

Hope this helps!

Trafalmadorian
Thanks i will figure it out from here on..
Rajeev
Awesome, thanks for accepting my answer :)
Trafalmadorian