Search code examples
jqueryjwysiwyg

Inject something in jWYSIWYG at cursor pointer?


I want to inject the dropdown selected value in jWYSIWYG at cursor pointer.I want to do is like that:

<select id="shirt" name="shirt">
      <option value="small">Small</option>
      <option value="medium">Medium</option>
      <option value="large">Large</option>
</select>
<a href="#" id="btn_insert" name="btn_insert">Insert</a>
<textarea id="testing_txt" name="testing_txt"></textarea>

Solution

  • The trick is to get the cursor position reliably. I found how to do this from an existing SO thread. Once you have the cursor position it is just a matter of getting the before and after text, then inserting your new value in the middle.

    http://jsfiddle.net/Vr99u/1/

    $("#mybutton").click( function() {
    var pos = getCaret(document.getElementById('mytextarea'));
    var currentText = $("#mytextarea").val();
    var currentTextStart = currentText.substr(0, pos);
    var currentTextEnd = currentText.substr(pos, currentText.length);
    var newText = currentTextStart + $("#myselect").val() + currentTextEnd;
    $("#mytextarea").val(newText); });
    
    
    function getCaret(node) {
      if (node.selectionStart) {
        return node.selectionStart;
      } else if (!document.selection) {
        return 0;
      }
    
      var c = "\001",
          sel = document.selection.createRange(),
          dul = sel.duplicate(),
          len = 0;
    
      dul.moveToElementText(node);
      sel.text = c;
      len = dul.text.indexOf(c);
      sel.moveStart('character',-1);
      sel.text = "";
      return len;
    }