aeran
aeran

Reputation: 1397

How to add / remove input value when clicking an element

I have this html elements:

<input type="text" name="myassetid"><img src=".." data-assetid="152"><img src=".." data-assetid="153"><img src=".." data-assetid="164">

When the user click , it will append the assetid value to input myassetid. When the user click the same element again, the assetid value should be removed from the input value (toggle).

I have this in my jquery:

$('img').click(function() {
  var assetid = $(this).attr('data-assetid');
  $(this).toggleClass("img-select");
  $('input[name="myassetid"]').val(function(i,val) { 
      return val + (!val ? '' : ',') + assetid;
  });
});

How do I code the removal part? Thanks.

Upvotes: 0

Views: 724

Answers (4)

Abdennour TOUMI
Abdennour TOUMI

Reputation: 93333

Enjoy Sorted result when appending /deleting Very Simple & optimal approach using Underscore Library:

 $('body').delegate('img[data-assetid]','click',function(){
     var target=$('input[name=myassetid]')
     var tarw=_.words(target.val(), ",");
     var app=$(this).attr('data-assetid');
    (tarw.indexOf(app)!==-1)?(tarw= _.without(tarw,app)):(tarw.push(app))
     target.val(_.sortBy(tarw,function (n) {return n}).join(','));
})

Demo : http://jsfiddle.net/abdennour/RrpLR/

Upvotes: 0

PSL
PSL

Reputation: 123739

Try this:-

This approach does not clear the values and recreate them. It just filters out the value.

Demo

See Array.filter for any refernce.

$('img').click(function() {
 var assetid = $(this).data('assetid');
  $(this).toggleClass("img-select");
    $this = $(this);
  $('input[name="myassetid"]').val(function(i,val) { 
      if($this.hasClass('img-select')){
          //append the value
          return val + (!val ? '' : ',') + assetid;
      }
      else
      {
          //remove the value
          return val.split(',').filter(function(ob){return parseInt(ob,10)!==assetid}).join(',');
      }
  });
});

Upvotes: 1

peterm
peterm

Reputation: 92805

Try

$('img').click(function() {
    $(this).toggleClass("img-select");
    var value = '';
    $('img.img-select').each(function(){
        value += (!value ? '' : ',') + $(this).attr('data-assetid');
    });
    $('input[name="myassetid"]').val(value);
});

jsFiddle

Upvotes: 1

Don McCurdy
Don McCurdy

Reputation: 11980

Here's one way to do it: just re-select all the selected images and rebuild the list each time a click event comes up.

var
$images = $('img'),
$input = $('input[name="myassetid"]');

$images.on('click', function () {
     var assetIds = [];

     $(this).toggleClass("img-select");

     $images.filter('.img-select').each(function () {
          assetIds.push($(this).data('assetid'));
     });

     $input.val(assetIds.join(', '));
});

Upvotes: 0

Related Questions