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 o
Solution 1:
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 falsyvar value = $('.avatar')
.filter(function() {
return $(this).data("selected");
})
.map(function() {
returnthis.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 falsyconst value = Array.from($('.avatar'))
.filter(elm => $(elm).data("selected"))
.map(elm => elm.id)
.join(",");
$("#selected-avatars").val(value);
});
Post a Comment for "Add/remove Comma-separated Input Values With Jquery"