ad...">

How to add and remove values ​​from a hidden input field?

<input type="hidden" id="values" value="1,2,1,3" /> <a href="#" id="add" data-value="4">add</a> <a href="#" id="remove" data-value="1">remove</a> <script type="text/javascript"> $(document).ready(function() { $('#add').click(function() { var value = $(this).attr('data-value'); //add to $('#values') return false; }); $('#remove').click(function() { var value = $(this).attr('data-value'); //remove all values that match in $('#values'); return false; }); }); </script> 

<strong> Examples

a) Add, the output will be: 1,2,1,3,4

b) Delete, the output will be 2.3

+4
source share
3 answers

You can achieve this with basic JavaScript functions and some jQuery goodies. See the documentation for the individual functions to learn more about them.

Add

 $('#values').val(function(i, v) { var arr = v.split(','); arr.push(value); return arr.join(','); // or actually easier in this case: // return v ? v + ',' + value : value; }); 

Delete

 $('#values').val(function(i, v) { return $.grep(v.split(','), function(v) { return v != value; }).join(','); }); 

Link: val , split , push , join , grep

Demo

+5
source

Add

 $('#add').click(function() { var values = $(this).attr('data-value'); alert($("#values").val()); $("#values").val($("#values").val() + values); alert($("#values").val()); return false; }); 

Delete will work the same.

you can get the value from hidden input with . val ()

0
source

you can use

  var str = $('#values').val() + value; $('#values').val(str); 

to add values ​​to the text box

0
source

All Articles