Greg McMullen Greg McMullen - 4 months ago 15
Javascript Question

JS Regex removes "too much" off of textarea

Working towards submitting a list of ID numbers to the DB. The JS is intended to add/remove the id # from each "tag" and save to the form.

In the example below, the list of

7,1,150
is pulled out of the DB, or was entered in that order by the user. Removing item #1 removes
,1,
from the list, as intended, but makes the list 7150 instead of 7,150.

I'm looking for a regex that would help eliminate this type of situation. I've had other issues with other number combinations as well. e.g.
17,160,7
Removing "7" takes out the
7,
of 17. Making the list
1160,7
.

"Working" Example. Removing Item 1, takes out both commas.

JS

$("#user-interests").on('click', '.tag', function(e){
e.preventDefault();
var txt = $(this).attr("id");
var group = $(this).data("group");
var regex = new RegExp("(\,)?"+txt+"(\,)?")
var textList = $("#"+group+" textarea");
console.log(txt);
if ( $(this).hasClass("active") ){
// Remove the class, and from the textarea
console.log("remove from list");
list = textList.text();
list = list.replace(regex, '');
$(textList).html(list);
$(this).removeClass("active");
} else {
console.log("Add to list");
textList.append(","+txt);
$(this).addClass("active");
}
$(this).parents("form").submit();
});


HTML

<div id="user-interests" class="profile-form active">
<button id="club-descriptions">Show Club Descriptions</button>
<div class="tags" id="club-list">
<textarea name="user[club-list]" class="form-control" id="club-list">7,1,50</textarea>
</div>
<div class="show-descriptions">
<button class="tag active" id="1" data-group="club-list">Item 1</button>
</div>
<div class="show-descriptions">
<button class="tag " id="7" data-group="club-list">Item 7</button>
</div>
<div class="show-descriptions">
<button class="tag " id="150" data-group="club-list">Item 150</button>
</div>
</div>


Note: I've also thought about using AJAX to submit each item instead of the entire form. Perfectly fine doing it that way if no other alternative is brought to light.

Answer Source

Using the code from @ewwink I was able to define an option that worked for me and cleaned up a lot of the code.

$("#user-interests").on('click', '.tag', function(e){
    e.preventDefault();
    var item = $(this).attr('id');
    var group = $(this).data('group');
    var $List = $("#"+group+" textarea");
    var list = ( $List.text() != "" ? $List.text().split(",") : [] );
    var index = list.indexOf(item);
    $(this).toggleClass("active");
    if ( index === -1 ){
        list.push(item);
    } else if ( index > -1 ) {
        list.splice(index, 1);
    }
    $List.html(list.join(","));
        $(this).parents("form").submit();
});

I'm also aware of issues with indexOf() but we're used to encouraging non-IE for some of our other existing products.