I have a jsp form in which the user is presented with multiple select boxes from which they can choose multiple options:
<td rowspan="4" colspan="1">Team Leaders<br />
<form:select id="teamLeader" multiple="multiple" size="10" path="teamLeader"/>
</td>
<td rowspan="4" colspan="1">HODs<br />
<form:select id="teamHod" multiple="multiple" size="10" path="teamHod"/>
</td>
<td rowspan="4" colspan="1">Directors<br />
<form:select id="teamDir" multiple="multiple" size="10" path="teamDir"/>
</td>
<td rowspan="4" colspan="1">Members<br />
<form:select id="teamPersons" multiple="multiple" size="10" path="teamPersons"/>
</td>
When the user clicks save, I want all options from all select boxes to be set to selected. I can achieve this by using a little jQuery method for each select box as follows:
jQuery(document).ready(function () {
jQuery('#saveButton').click(function () {
jQuery('#teamPersons').each(function () {
jQuery('#teamPersons option').attr("selected", "selected");
});
});
});
However the problem is that I have to write a method for each of the 4 select boxes. Is there an easier way to do this i.e. write a single jQuery method to set all options to selected?
The simplest way to select every single item on click, would be as follows:
$("select[multiple] option").prop("selected", "selected");Example fiddle: http://jsfiddle.net/vYzUS/
In the fiddle, I’ve omitted the button click and turned the HTML into dummy HTML. I’ve also (arbitrarily) added the multiple attribute, incase you have any other
selectlists that you do not want to be selected. It might be more advisable to wrap the ones you do want to select in adivwith anid, as it will give the selector a better focus.I’ve also used
.prop()instead of.attr()–.prop()was introduced in jQuery 1.7 and is specifically for retrieval/setting of property values.