Sylar Sylar - 7 days ago 9
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
toggleClass
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 />


JS:

$('.avatar').click(function(){
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

//$(this).toggleClass('avatar-circle-display-loop-select')
});


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.

Answer

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:

$('.avatar').click(function(){
    var $this = $(this);
    $this.data("selected", !$this.data("selected")); // Will be `undefined`
                                                     // initially, which is falsy
    var value = $('.avatar')
        .filter(function() {
            return $(this).data("selected");
        })
        .map(function() {
            return this.id;
        })
        .get()
        .join(",");
    $("#selected-avatars").val(value);
});

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

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