Javascript functions for form fields

A number of useful functions for accessing various properties and values of form fields.

Getting the selected index and value from a select list

function getValues(){
var dd = document.getElementById('dropdown');
theindex = dd.options[dd.selectedIndex].value;
thevalue = dd.options[dd.selectedIndex].text;
var span = document.getElementById('span1');
span.innerHTML = '  Selected Index: ' + theindex + 
	', Selected Value: ' + thevalue
}

Detect which checkbox was ticked or unticked, and an array of selected values

function getchk(val){
var output = 'You clicked ' + val + ' Selected: ';
for(var i = 0; i < document.forms[0].check.length; i++){
	if(document.forms[0].check[i].checked)
	output += document.forms[0].check[i].value + ' ';
	}
document.getElementById('span2').innerHTML = output;
}

1
2
3
4

Get the text and number of characters from a text box

function getText(){
var txt = document.getElementById('txt');
var output = txt.value;
var length = output.length;
document.getElementById('span3').innerHTML = 'Count: ' + length
	+ ' Text: ' + output;
}