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>