使用 JavaScript 函数很容易。将此添加到您的页面之间<script>
和</script>
标签之间:
var selected = {};
function validate(obj)
{
for (var i = 0; i < obj.options.length; i++) {
if (obj.options[i].selected) {
selected[obj.id+'_'+obj.options[i].value] = obj.options[i].label;
}
else {
selected[obj.id+'_'+obj.options[i].value] = null;
}
}
var size = 0;
for (var key in selected) {
if (selected[key] != null) { size++; }
}
//console.log(size);
if(size > 3){
alert("You can only select a maximum of three options.");
}
}
然后改变你<apex:inputField>
的样子:
<apex:inputField value="{!Agency_Profile.Destination_ Specialties}" onchange="validate(this);"></apex:inputField>
这是一个完整的 Visualforce 页面示例:
<apex:page >
<script>
var selected = {};
function validate(obj)
{
for (var i = 0; i < obj.options.length; i++) {
if (obj.options[i].selected) {
selected[obj.id+'_'+obj.options[i].value] = obj.options[i].label;
}
else {
selected[obj.id+'_'+obj.options[i].value] = null;
}
}
var size = 0;
for (var key in selected) {
if (selected[key] != null) { size++; }
}
//console.log(size);
if(size > 3){
alert("You can only select a maximum of three options.");
}
}
</script>
<apex:form >
<apex:selectList id="chooseColor1" size="5" multiselect="true" onchange="validate(this);">
<apex:selectOption itemValue="white" itemLabel="White"/>
<apex:selectOption itemValue="red" itemLabel="Red"/>
<apex:selectOption itemValue="orange" itemLabel="Orange"/>
<apex:selectOption itemValue="green" itemLabel="Green"/>
<apex:selectOption itemValue="blue" itemLabel="Blue"/>
</apex:selectList>
<apex:selectList id="chooseColor2" size="5" multiselect="true" onchange="validate(this);">
<apex:selectOption itemValue="white" itemLabel="White"/>
<apex:selectOption itemValue="red" itemLabel="Red"/>
<apex:selectOption itemValue="orange" itemLabel="Orange"/>
<apex:selectOption itemValue="green" itemLabel="Green"/>
<apex:selectOption itemValue="blue" itemLabel="Blue"/>
</apex:selectList>
</apex:form>
</apex:page>