mlclm mlclm - 3 months ago 28
HTML Question

jQuery on string click, add or remove text matched within textarea

I have a list of word inside a

<ul>
tag, I'm trying to add the word from that li inside a textarea when user clicks on the
<li>
element. The word is added properly, but I'm trying to remove that word from the textarea if the user clicks on that same
<li>
element.

<ul>
<li>Word One</li>
<li>Word deux</li>
<li>Other Word three</li>
<li>yet another Word 4</li>
</ul>

<textarea id="list" rows="4" cols="20"></textarea>


jQuery

jQuery(document).ready(function() {

// removing the textarea value when window is loaded again
// otherwise for some reason all the values entered before are still there ?

jQuery(window).load(function() {
jQuery('#list').val('');
})

jQuery('ul li').click(function(addWord) {

var choice = jQuery.trim($(this).text());
var textArea = jQuery("#list");

// if the <li> with the word was allready clicked, then remove its "selected" class
if (jQuery(this).hasClass('selected')) {
jQuery(this).removeClass('selected');

//textArea.replace(choice,'');

} else {
// add class selected to the clicked <li> word, add the word to the textarea
jQuery(this).addClass('selected');
textArea.val(textArea.val() + choice + ' , ').text(textArea.val());
}
});
}

Answer

You need to replace the text when you are removing selected class. Here .val(function) is used.

jQuery(document).ready(function() {

  jQuery('ul li').click(function(addWord) {

    var choice = jQuery.trim($(this).text());
    var textArea = jQuery("#list");

    // if the <li> with the word was allready clicked, then remove its "selected" class
    if (jQuery(this).hasClass('selected')) {
      jQuery(this).removeClass('selected');

      textArea.val(function(_, val) {
        return val.replace(choice + ' , ', '');
      });
    } else {
      // add class selected to the clicked <li> word, add the word to the textarea
      jQuery(this).addClass('selected');
      textArea.val(function(_, val) {
        return val + choice + ' , ';
      });
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>Word One</li>
  <li>Word deux</li>
  <li>Other Word three</li>
  <li>yet another Word 4</li>
</ul>

<textarea id="list" rows="4" cols="20"></textarea>