Adding and removing from checkbox to hidden input
by sparksterz
HTML
<div id="myForm"></div>
<input type="checkbox" id="MyHundredField" value="100" checked>
<button id="list">List the stored vals</button>
JavaScript
String.prototype.splitCSV = function (sep) {
for (var foo = this.split(sep = sep || ","), x = foo.length - 1, tl; x >= 0; x--) {
if (foo[x].replace(/"\s+$/, '"').charAt(foo[x].length - 1) == '"') {
if ((tl = foo[x].replace(/^\s+"/, '"')).length > 1 && tl.charAt(0) == '"') {
foo[x] = foo[x].replace(/^\s*"|"\s*$/g, '').replace(/""/g, '"');
} else if (x) {
foo.splice(x - 1, 2, [foo[x - 1], foo[x]].join(sep));
} else foo = foo.shift().split(sep).concat(foo);
} else foo[x].replace(/""/g, '"');
}
return foo;
};
Array.prototype.remove = function (from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
var values = ["dsfsdfd", "100", "!@#!$%$#%^$#^"];
var input = "<input type='hidden' id='myHiddenStuff' value='" + values + "'>";
$("#myForm").append(input);
$("#MyHundredField").on("change", function (e) {
if (e.currentTarget.checked) {
//If Add
var selected = e.currentTarget.value;
var valueArray = $("#myHiddenStuff").val().splitCSV();
valueArray.push(selected);
$("#myHiddenStuff").val(valueArray);
} else {
//If Remove
var selected = e.currentTarget.value;
var valueArray = $("#myHiddenStuff").val().splitCSV();
var positionToRemove = -1;
$(valueArray).each(function (idx, elm) {
if (elm == selected) {
positionToRemove = idx;
}
});
if (positionToRemove >= 0) {
valueArray.remove(positionToRemove);
$("#myHiddenStuff").val(valueArray.toString());
}
}
});
$("#list").on("click", function (e) {
alert($("#myHiddenStuff").val());
});