我有一个inputField绑定到多选自定义字段。
我想验证用户从列表中选择最多3个项目,并且我想在用户立即选择第四个项目时显示消息或警告(而不是在提交表单时)。我发现actionSupport可以帮助我,但我不确定它是否可以让我跟踪选择了多少项
<apex:inputField value="{!Agency_Profile.Destination_ Specialties}">
<apex:actionSupport event="onchange" action="{}" />
</apex:inputField>
答案 0 :(得分:1)
使用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>