Getting Form Values with Javascript

I am building a CRM/Scripting System/Scheduler for a client and I needed an easy wrapper function to quickly grab the value of a form input with javascript. I use alot of AJAX and was noticing that I was repeating the same set of code over and over and over and over…. You get the jist 🙂 In programming this is a bad idea. You want to strive for reusable code. Now the code I was writting over again is pretty simple but I still wanted to save myself some typing, another thing you strive for as a programmer, so I came up with a couple simple wrapper functions that will get me the value of a form input with a single function call.

Without further ado:

/**
 * Returns the value of a select box. It will 
 * work for both a multiselect box and a normal
 * select box.
 *
 * The function returns an string of the selected
 * values separated by a ','.
 */
function getSelectValue(selID) {

	var selectList = document.getElementById(selID);
	var optionsLength = selectList.options.length;
	
	var results = "";
	
	for (gsv_i = 0; gsv_i < optionsLength; gsv_i++) {
		if (selectList.options&#91;gsv_i&#93;.selected) {
			value = selectList.options&#91;gsv_i&#93;.value
			if (results == "") {
				results = results + value;
			} else {
				results = results + "," + value;
			} 
		}
	}

	return results;
}

/**
 * Returns the value of a form input.
 */
function getInputValue(id) {

	if (document.getElementById(id).type.indexOf('select') != -1) {
		// We have a select element. Lets call the function for selects.
		return getSelectValue(id);
	} else {
		// Else we will just return the value of the element
		return document.getElementById(id).value;
	}
	
}

/**
  * USAGE 
  */

function getTestValues() {
	var inputValue = getInputValue('textInput');
	var selectValue = getInputValue('selectInput');

	alert(inputValue);
	alert(selectValue);

	return false;
}

&#91;/sourcecode&#93;

And now for the HTML:

&#91;sourcecode language='html'&#93;
<input type="text" name="textInput" id="textInput" value="Some Value" />
<select name="selectInput" id="selectInput">
	<option value="option 1">Option 1</option>
	<option value="option 2">Option 2</option>
	<option value="option 3">Option 3</option>
</select>

<script type="text/javascript">
	getTestValues();
</script>

Since I’m not a Javascript guru I am not guaranteeing this is the best way to do this. It is just what I found most convenient for me and I believe will be convenient for others 🙂

I hope you enjoy and if you have questions feel free to ask 🙂

Later!
– Miah


I believe that’s the dance of a brave little toaster.” – Xander, Something Blue

Advertisement