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
user317005
source share3 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(','); }); +5