Sylar Sylar - 1 month ago 18
Javascript Question

Add/Remove comma-separated input values with jquery

I can add values to an input and remove but what I want to achieve looks messy.

I have two images that when clicked, gives me their user id. So when clicked, a hidden input value of 1 is added. When the other image is clicked, same:

<input id="selective-avatars" name="avatars[]" type=hidden value="1,2" />

If same image is clicked, again, their id is removed (like a
sort of thing). That is the tricky part I face with piecing the two links together.

Full HTML (example):

<img src="url" id="1" class="avatar" />
<img src="url" id="2" class="avatar" />
# Should this be in the loop also? It's currently not.
<input id="selective-avatars" name="avatars[]" type=hidden />


let {id} = this;
//let array = $('#selective-avatars').val().split(',');
$('#selective-avatars').val(function(i, val){
return [val + (!val ? '' : ',') + id];
//Removed about 8 lines as nothing works


I was trying not going the react route as I wanted to use pure jquery in the side project.

All I want is
<input id="selective-avatars" name="avatars[]" type=hidden value="1,2, etc" />
going to the controller.


It looks like the id on the .avatar elements tells us what values to include in the hidden input. I'd keep a flag on the element and just rebuild the input value every time:

    var $this = $(this);
    $"selected", !$"selected")); // Will be `undefined`
                                                     // initially, which is falsy
    var value = $('.avatar')
        .filter(function() {
            return $(this).data("selected");
        .map(function() {

I notice you've used ES2015 and above features, so in ES2015:

$('.avatar').click(function() {
    const $this = $(this);
    $"selected", !$"selected")); // Will be `undefined`
                                                     // initially, which is falsy
    const value = Array.from($('.avatar'))
        .filter(elm => $(elm).data("selected"))
        .map(elm =>