append text in cusor position if cursor not present should append at end of existing text value is taken from dropdown when clicking a button
<p>I Want to append the text at the cursor position when cursor is placed else want to append it at the end of the existing text. Its working fine if i am using a button value for appending i would also want when i am using a dropdown selected value to be appended at end of text if cursor is not present else at cursor postion when i click a button.</p>

<pre><code>function insertAtCursor(text) 
{
  var field = document.getElementById("Expression");
  if (document.selection) 
  {
    var range = document.selection.createRange();
    if (!range || range.parentElement() != field) 
    { 
        field.focus();
        range = field.createTextRange();
        range.collapse(false);
    }
    range.text = text;
    range.collapse(false);
    range.select();
  }
  else if (field.selectionStart || field.selectionStart == '0')
  {
     var startPos = field.selectionStart;
     var endPos = field.selectionEnd;
     field.value = field.value.substring(0, startPos)+ text+ field.value.substring(endPos, field.value.length);
  }
  else 
  {
     field.value += text;
  }
}

function addSyntax()
{
   var field = document.getElementById("operatorSelect"); 
   var value  = '';
   if( field != '') 
   {
       value = field.options[field.selectedIndex].value;
   insertAtCursor(value)
       field.selectedIndex = 0;
   }
}


&lt;html&gt;
&lt;body&gt;
&lt;input type="button" unselectable="on" value="Insert text" onmousedown="insertAtCursor('[INSERTED]'); return false"&gt;

&lt;input type=button unselectable="on" value=" ( " onmousedown="insertAtCursor('('); return false"&gt;&amp;nbsp;&amp;nbsp;

&lt;br&gt;

&lt;textarea id="Expression" rows="5" cols="50"&gt;Put the caret in here and press the button or click outside and then press the button.&lt; /textarea&gt;

&lt;select name="operatorSelect"&gt;

&lt;option value=null&gt;------ Select Operator ------&lt; /option&gt;

&lt;option value="&amp;#60;"&gt;&lt; &amp;nbsp;&amp;nbsp;&amp;nbsp;(Less&amp;nbsp;Than)&lt; /option&gt;

&lt;option value="&amp;#60;="&gt;&lt; =&amp;nbsp;(Less&amp;nbsp;Than&amp;nbsp;Or&amp;nbsp;Equal&amp;nbsp;To)&lt; /option&gt;

&lt;option value="!="&gt;!=&amp;nbsp;&amp;nbsp;(Not&amp;nbsp;Equal&amp;nbsp;To)&lt; /option&gt;

&lt;option value="="&gt;=&amp;nbsp;&amp;nbsp;&amp;nbsp;(Equal&amp;nbsp;To&amp;nbsp;or&amp;nbsp;IN)&lt; /option&gt;

&lt;option value="&amp;#62;"&gt;&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;(Greater&amp;nbsp;Than)&lt; /option&gt;

&lt;option value="&amp;#62;="&gt;&gt;=&amp;nbsp;(Greater&amp;nbsp;Than&amp;nbsp;Or&amp;nbsp;Equal&amp;nbsp;To)&lt; /option&gt;

&lt;option value="NOT IN"&gt;NOT&amp;nbsp;IN&lt; /option&gt;

&lt;/select&gt;

&lt;input type=button  unselectable="on" value=" Add Expression " onmousedown="addSyntax();
return false"&gt;&amp;nbsp;&amp;nbsp;
</code></pre>

<p>Please help me in this.</p>

<p>Thanks in advance.</p>
