Javascript: Add values to CSV if not in CSV - if Already in CSV - remove from CSV
I am building a CSV string - so everything a user clicks a div - a开发者_JAVA技巧 string of 5 characters gets passed into a hidden field - what I am trying to do is to append each new value and create a CSV string - when done - display in a textbox - if the value being passed into the CSV already exists - remove it and then, just like before, display CSV in the textfield. I have the below, but it just does not work...
function newQuery(val, id) {
var xy = document.getElementById(id);
var x = parent.document.getElementById('txtCriteria');
var myValue = parent.document.getElementById('txtCriteria').value;
var hdn = document.getElementById("hdnSearch");
hdn.value += "," + val;
var element = hdn.value;
var fin;
var leadingComma = element.substring(1, 0).toLowerCase();
var trailingComma = element.substring(element.length - 1);
// Check for leading comma
if (leadingComma == ",") {
fin = element.substring(1);
}
// Check for trailing comma
if (element.charAt(element.length - 1) == ",") {
fin = element.slice(0, -1);
}
if (x.value.search(val) == 0) {
alert('Already exists');
fin.replace(val, "");
x.value = fin;
// Set image to checked
xy.src = 'bullet_plus.png';
}
else if (element.search(val) > 0) {
alert('New Selection: ' + fin);
x.value = fin;
// Set image to checked
xy.src = 'bullet_tick.png';
}
}
When handling CSV I recommend you use Array.join
and String.split
var foo = "hello, there, so";
var arr = foo.split(","); // ["hello", " there", "so"];
var bar = arr.join(","); // "hello, there, so"
As for your code it makes little sense without the HTML or without having useful variable names.
A set data structure eliminates a lot of unnecessary work:
function CsvSet(str) {
var set = {};
var arr = str.split(",");
for (var i = 0; i < arr.length; i++)
set[arr[i]] = true;
this.set = set;
}
CsvSet.prototype.put = function(val) {
this.set[val] = !this.set[val];
}
CsvSet.prototype.toString = function() {
var res = [];
for (var val in this.set) {
if (this.set[val])
res.push(val);
}
return res.join();
}
Now let's add and remove some items:
var set = new CsvSet("one,two,three");
set.put("one"); // remove
set.put("seven"); // add
set.toString();
Output:
"two,three,seven"
精彩评论