Moved to: WoodyHayday.com
Woody Hayday

Fresh Ideas

Hi there! This is my old blog, I don't hang around here much.
You can now find me trying to mix things up here:
Visit WoodyHayday.com Subscribe To My Email List

Maintain a CSV with Javascript – keep a hidden list

The situation: Want to build a comma separated list of int’s (or whatever) client-side, in javascript, remove/add items on the fly using JS. Well these tiny functions below are what I use, useful when you just need to get a clever form / app input done.

Using the below you can add/remove items to an input which acts as a csv holder, should be self explanatory, get and set are just shorteners.

function get(a){ //small get
	if (typeof a != "undefined") {
		return document.getElementById(a).value;
	} else { 
		return '';
	}
}

function set(i,v){ //small set
	document.getElementById(i).value = v;	
}

function append(i,v){ //small append
	set(i,get(i) + v);		
}

function appendTocsv(i,v){ //small append csv
	if (get(i).length == 0){
		set(i,v);	
	} else { 
		append(i,', ' + v);
	}
}

function incsv(id,v){ //check a csv (in element with id) for a value (v)
	
	var csv = get(id);
	var csvArray = csv.split(', ');
	var found = false;
	
	if (csvArray.length > 0){
		
		for (i = 0; i <= csvArray.length; i++){
		
			if (csvArray[i] == v){ found = true;  }
			
		}
		
	}
	
	return found;
		
}

function removeFromcsv(id,v){ //removes a val from csv
	
	var csv = get(id);
	var csvArray = csv.split(', ');
	var removed = false;
	var endString = "";
	
	if (csvArray.length > 0){
		
		for (i = 0; i <= csvArray.length-1; i++){
		
				
			if (csvArray[i] == v){ removed = true;  } else { 
			
				if (endString.length > 0){ endString += ', '; } 
				endString += csvArray[i]; 
			
			}
			
		}
		
	}
	
	set(id,endString);
	
	return removed;
	
}
This entry was posted in Javascript, Snippets, Web Development and tagged , , , . Bookmark the permalink. Both comments and trackbacks are currently closed.

One Trackback

  1. […] This rar includes my csv quick maintaining functions which are required. This entry was posted in Javascript, Web Technology and tagged autosuggest, […]

Woody Hayday

Comments Archive

Hi there. This is my old blog and it's archived, so you can no longer post new comments on this post (Maintain a CSV with Javascript – keep a hidden list).

Read my new blog about writing software and stories at WoodyHayday.com

The New Blog
WoodyHayday.com
A Quote..
"I never took drugs because I am drugs"
Salvador Dali
Old Random Projects
    © Woody Hayday 2008-2024