Search code examples
javascriptcursortextarea

Insert text into a <textarea> when a button is clicked, where the cursor was positioned


I have a <textarea> with several buttons underneath it, and the purpose of these buttons is to insert certain text in to the <textarea>.

The below code will always insert the desired text at the beginning of the <textarea>, which is fine if it didn't have focus when the button was clicked. However, if the <textarea> did have focus, I'd like to insert the text where the cursor was when a button is clicked.

Here is my code so far. If anyone can suggest how I would need to do this, I'd be very grateful. Thanks.

jQuery(document).ready(function(){

    var button_text = {} // The text to insert for each button click

    button_text['insert_event_name']        = 'event_name';
    button_text['insert_event_date']        = 'event_date';
    button_text['insert_event_start_time']  = 'event_start';
    button_text['insert_event_finish_time'] = 'event_finish';
    button_text['insert_event_location']    = 'event_location';
    button_text['insert_event_address']     = 'event_address';

    jQuery('.inserter', '#event-desc-container').on('click', function(){

        var button = jQuery(this).attr('name');
        var text = '['+button_text[button]+']';

        textarea = jQuery('textarea#event_desc', '#event-desc-container');
        desc = textarea.val()

        textarea.val(text+desc);

    });

});

Solution

  • Can be easily done with this jQuery plugin: http://dwieeb.github.io/jquery-textrange/