This is a live demo page. Go back to the main article

Javascript plugin to get or set current caret position (cursor location) in textarea/input, to get selected value under textarea/input and replace selected value.


    /*
        $textArea.GetCaretPos(element) -> Returns no as current cursor position at characters
        
        $textArea.SetCaretPos(element, position) -> Sets cursor position to mentioned character index
        
        $textArea.GetSelectedVal(element) -> Returns text selected value
        
        $textArea.ReplaceSelectedVal(element,text) -> Replaces selected text with text supplied
    */
    
    function wrapTag(elem,tag)
    {
        /*Selected value from textarea*/        
        var selectedVal = $textArea.GetSelectedVal(document.getElementById(elem));    
        
        /*Add tag only if text is selected */
        if(selectedVal.length>0)
        {
            /*Current cursor/caret position*/
            var curPos  = $textArea.GetCaretPos(document.getElementById(elem));    
            
            /*Text to replace current selected value*/
            var textToReplace = "<"+tag+">"+selectedVal+"";    
            
            /*Replace current selected value with new value*/
            $textArea.ReplaceSelectedVal(document.getElementById(elem),textToReplace);               
            
            /*Set focus to textarea*/
            document.getElementById(elem).focus();        
            
            /*Set cursor/caret position just after newly added text*/
            $textArea.SetCaretPos(document.getElementById(elem),curPos + textToReplace.length);       
        }
    }  
    

An example of use



Bold Italic Underline

Bold Italic Underline

Works with input box as well


Bold Italic Underline
This is a live demo page. Go back to the main article

© Vipul Limbachiya