I need to do validation that at least one element is selected. This element was filled dynamically and I need to validate if that I have at least one option element selected, using validation Engine.
Here fill the select option item
jQuery("#bt_add").click(function(){
storeUsedGroups[attr_group.val()] = true;
jQuery("#atributo_id").append('<option value='+attr_name.val() +
' groupid='+attr_group.val()+'>' + attr_group.text() +
' : ' + attr_name.text()+'</option>'
);
});
and validate with required, but for submit form need select the options inserted.
<select name="atributo_id[]" id="atributo_id" multiple="multiple" class="validate[required]">
<option value="5" groupid="1">Color : Azul</option>
</select>
I just need to validate non-empty the element.
UPDATE: If I understand you correctly you want to apply required rule only if select element was populated with options.
You can do that with custom function call. Change your select's class to
<select name="atributo_id[]"
id="atributo_id"
multiple="multiple"
class="validate[funcCall[ifSelectNotEmpty]]">
Now the function
function ifSelectNotEmpty(field, rules, i, options){
if ($(field).find("option").length > 0 &&
$(field).find("option:selected").length == 0) {
// this allows the use of i18 for the error msgs
return "* This field is required";
}
}
It supposed to be working, but it won't because jquery.validationEngine.js
crashes on line 707 (IMHO it's a bug). So you need to change line 707 from
if(!required && && !(field.val()) && field.val().length < 1) options.isError = false;
to
if(!required && !field && !(field.val()) && field.val().length < 1) options.isError = false;
^^^^^^
Original answer If you want to check if any of options has been selected you can do it like this
if (!$("#atributo_id option:selected").val()) {
alert("Nothing has been selected");
}
or
if (!$("#atributo_id option:selected").length) {
alert("Nothing has been selected");
}