No biggie. This was just one of those times where I got carried away with the code. I made yet another version which now uses arrays instead of regular expression to format the output when there are more than one items selected. This is supposed to be more efficient, though in this case I'm not really sure. I also now take into account the possibility that no items might be selected. Both my versions work off the form as passed in the onclick event, rather than naming it in the function:
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function check(theForm, theList){
theForm = theForm.tagName.toLowerCase() === 'form'? theForm : theForm.form;
theList = theForm.elements[theList];
var chkmsg = '', intro = 'The selected text value', qntfyr = ' is: ', add = '', i = 0, last = '';
for (i; i < theList.length; ++i) {
if (theList.options[i].selected === true) {
if (chkmsg.length && !add){
add = ', ';
qntfyr = 's are: ';
}
chkmsg = [chkmsg, add, theList.options[i].text].join('');
}
}
chkmsg = chkmsg.split(',');
if (chkmsg.length > 1){
last = [', and', chkmsg.pop()].join('');
}
if (chkmsg[0]){
alert([intro, qntfyr, [chkmsg.join(','), last].join(''), '.'].join(''));
}
else{
alert('No items selected.');
}
}
</script>
</head>
<body>
<form action="#">
<div>
<select name="myList" multiple>
<option value=1>One</option>
<option value=2>Two</option>
<option value=3>Three</option>
<option value=4>Four</option>
</select>
<p>
<input type="button" value="Get Text Value" onclick="check(this, 'myList')">
</p>
</div>
</form>
</body>
</html>
Bookmarks