|
Handling multiple Select options with JavaScript
While the HTML Select form control allows multiple selections, you may have wondered
how to manipulate those selections, for inclusion in a database, for example.
ASP offers several ways to do so. Of course, client-side script and the DOM give
you one way to do so. When you use this technique, the basic idea consists of looping
through the control's options, check each option's Selected property, and where
appropriate, enter the value and text directly into a database or an array, as seen below:
<head>
<script language="JavaScript">
function getSelected() {
var sConnect = "Provider=Microsoft.Jet.OLEDB.3.51;Data " +
"Source=D:\\Inetpub\\wwwroot\\ZDJindex\\index.mdb"
var adoRst = new ActiveXObject("ADODB.Recordset")
adoRst.open("tblDays", sConnect, 2, 2) //2-dynamic keyset, 2-table command
var objSelect = document.forms["frm1"].elements["sel1"]
var msg = new String("")
//Insert selected items
for (x=0; x<objSelect.length; x++) {
if (objSelect.options[x].selected) {
adoRst.AddNew()
adoRst.Fields("Day") = objSelect.options[x].text
adoRst.Fields("Value") = objSelect.options[x].value
adoRst.Update()
msg += objSelect.options[x].text + ", "
}
}
adoRst.close()
//Strip the trailing comma
msg = msg.substring(0, msg.length-2)
//Show selected items
alert(msg)
}
</script>
<body>
<form id="frm1">
<select size=10 multiple="multiple" id="sel1">
<option value="1">Sunday</option>
<option value="2">Monday</option>
<option value="3">Tuesday</option>
<option value="4">Wednesday</option>
<option value="5">Thursday</option>
<option value="6">Friday</option>
<option value="7">Saturday</option>
</select>
<input type="button" value="Show Selections" onclick="getSelected()"
/>
</form>
</body>
While this script works just fine on the client-side in Internet Explorer,
don't try the same technique when you post a form to server-side
ASP. That's because the multiple selections get passed as a comma-delimited
string. In an upcoming tip, we'll show you two different ways parse this string on the
server side.

|