0

I have a sample code:

<input type="hidden" value="" name="stall_id">
<a href='javascript:;' onclick='check(this)' data-id='1'>Add</a>
<a href='javascript:;' onclick='check(this)' data-id='2'>Add</a>
<a href='javascript:;' onclick='check(this)' data-id='3'>Add</a>

My jquery:

function check(tr) {
    var id = $(this).data("id");
    $(tr).attr("onclick", "uncheck(this)");
    $(tr).html('Add');
}
function uncheck(tr) {
    var id = $(this).data("id");
    $(tr).attr("onclick", "check(this)");
    $(tr).html('Remove');
}

How to when check/uncheck, value will auto add on input hidden ?

Ex: <input type="hidden" value="1,3" name="stall_id"> if I had checked two value.

Hai Truong IT
  • 4,126
  • 13
  • 55
  • 102

3 Answers3

0

input type hidden can only have a literal value. If you use a comma separated string, you can elaborate it and transform it in an array. Alternatively you can use form input arrays. You can find some more information here. Basically you'll need to create an input hidden (dynamically) for each value and set the name to "stall_id[]"

Community
  • 1
  • 1
Luca Simonetti
  • 127
  • 1
  • 8
0

You don't need to change onclick attribute of a try this code will work fine for you use only single function:-

function check(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);
   alert(hdn.val());
 }   

Demo

Umesh Sehta
  • 10,555
  • 5
  • 39
  • 68
0

This should work:

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(','));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.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>

We're attaching a class "checked" to checked elements so that we can simply select all checked elements using jQuery's class selectors.

martynasma
  • 8,542
  • 2
  • 28
  • 45