Search code examples
javascriptjquerytextboxcode-completion

jQuery Code Completion Style Textbox Typing


Does anyone know of a function or plugin to jQuery (or pure JS, doesn't matter) that will perform a code completion type function? But with change-able options? Like I want to start typing [b] and when I add that last bracket, it automatically adds [/b] after the cursor? If anyone knows anything like this, it would be great and a gigantic time saver.


Solution

  • By using JQuery Caret Plugin, you could use some code like:

    <textarea id="codeInput" cols="80" rows="50">content</textarea>
    <script type="text/javascript">
    
        var tagDict = {
          "[b]" : "[/b]",
          "[c]" : "[/c]",
          "[d]" : "[/d]"
        };
    
        $(document).ready(function () {
            $('#codeInput').keyup(function () {
                var test = $(this).val();
                var tagStart = test.substr(test.length - 3, 3);
                if (tagDict[tagStart]) {
                    $(this).val(test + tagDict[tagStart]);            
                    $(this).caret(test.length, test.length);
                }
            });
        });
        </script>
    

    It's not perfect, but it could be a start for a complete code completion function.