Onclick Add/Remove specific string from textarea using jQuery

Viewed 110

I've got a form with some selects that auto populate a sentence in a textarea, however, I wan't to be able to then remove the sentence it has added to the textarea if they click it again.

I would just clear the entire textarea value but that wouldn't work as they may have clicked 2 prefills and I only want to remove the specific content added by the prefill they're clicking.

    var contactTextarea = jQuery('.form-contents .ori-textarea .query-textarea-ori');

    jQuery( "#query-telcoedge" ).click(function() {
        prefill = jQuery(this).attr('rel');

        if(jQuery(this).hasClass('active')){

        } else {
            contactTextarea.val(contactTextarea.val() + prefill + '\n');
        }

        jQuery(this).toggleClass('active');
    });

enter image description here

1 Answers

To remove the text, you can use .replace.

This will remove only the first match, so if the user copies your text so it appears twice, only the first will be removed. To remove all you can use .replaceAll. (not IE11)

If the text has been changed by the user, it won't remove it

if (jQuery(this).hasClass('active')) {
    contactTextarea.val(contactTextarea.val().replace(prefill + '\n', ""));
} else ...
Related