so test of two answers

Benchmark created on


Preparation HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<input type="text" value="" name="stall_id">
<a href='javascript:;' onclick='toggle(this)' data-id='1'>Add</a>
<a href='javascript:;' onclick='toggle(this)' data-id='2'>Add</a>
<a href='javascript:;' onclick='toggle(this)' data-id='3'>Add</a>

Test runner

Ready to run.

Testing in
TestOps/sec
martynasma
function toggle(tr) {
  if ($(tr).hasClass("checked")) {
    $(tr).removeClass("checked").html("Add");
  } else {
    $(tr).addClass("checked").html("Remove");
  }
  var selected = [];
  $("a.checked").each(function() {
    selected.push($(this).data("id"));
  });
  $("input[name=stall_id]").val(selected.join(','));
}
ready
Learner
function toggle(tr) {
  var id = $(tr).data("id");
  var hdn = $('[name="stall_id"]'),
    val;
  var text = $(tr).html();
  if (text == 'Add') {
    val = hdn.val() == '' ? id : hdn.val() + ',' + id;
  } else {
    val = hdn.val().split(',').filter(function(d) {
      return d != id;
    }).join(',');
  }
  $(tr).html(text == 'Add' ? 'Remove' : 'Add');
  hdn.val(val); 
}
ready
function toggle(tr) {
  var id = $(tr).data("id");
  var hdn = $('[name="stall_id"]'),
    val;
  var text = $(tr).text();
  if (text == 'Add') {
    val = hdn.val() == '' ? id : hdn.val() + ',' + id;
  } else {
    val = $.grep(hdn.val().split(','),function (d) {
            return d != id;
        }).join(',');
  }
  $(tr).text(text == 'Add' ? 'Remove' : 'Add');
  hdn.val(val);  
}
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.