I’m trying to figure out how to sync two multiple choice lists in javascript. Here’s the code which works:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Untitled Page</title>
</head>
<script language="JavaScript">
<!--
function SelectEmail(name)
{
var listboxEmails = document.getElementById('emails');
for (var i=0;i<listboxEmails.length;i++)
{
listboxname = listboxEmails[i].innerHTML
if (listboxname == name)
{
listboxEmails.selectedIndex = i;
break;
}
}//end for
}//end function SelectEmail
// -->
</script>
<body>
<select id='names' name ='names' style = "width: 100" multiple="multiple" onClick="SelectEmail(this.value);">
<option value ="joe">joe</option>
<option value ="albert">albert</option>
<option value ="gary">gary</option>
<option value ="ace">ace</option>
</select>
<select id="emails" name ="emails" style = "width: 100;" multiple="multiple">
<option value ="joe@asds.com">joe</option>
<option value ="albert@asds.com">albert</option>
<option value ="gary@asds.com">gary</option>
<option value ="ace@asds.com">ace</option>
</SELECT>
</body>
</html>
However I want to make it show multiple choices. So for example if I choose albert and gary on the left list, I want the right list to select albert and gary as well. Please help me with this. Cheers.
Your function
SelectEmail()can’t work because it setsselectedIndexof your select, which selects one option and deselects the rest. Also, you are using the text content of the options in#emailsin order to map them with the values of#names. That’s not a good practice, because text nodes are supposed to show text and not to enable the identification of elements in your script.Instead, you can access the
selectedattribute separately for each option you want to select. By adding an additional attribute to your#emailselement’s options, it could look like:You can now use the
data-nameattribute to map the options, for example in the following way:Here’s a working fiddle (you will notice that I also used the
onchangeevent instead ofonclick:http://jsfiddle.net/H9hNH/2/