here i am giving my html. i have a dropdown which showing few product info and showing hobbies by checkbox. i want if user select product iPod then validation w
You have some errors in the produced HTML:
You may use the jQuery validator to add a new rule to repeat exactly what you do in your two jQuery functions:
You forgot to give the Hobbies-error element, so I used a div.
In the following the snippet:
var validator;
// a new rule is required to test if iPod is selected and checkboxes are...
$.validator.addMethod('checkboxMaxIfiPodNotSelected', function (value, elem, param) {
var selectedOptionVal = $(param.selEleiSiPod).val().trim();
var selectedOptionText = $(param.selEleiSiPod).text().trim();
if (selectedOptionText != 'iPod') {
if (selectedOptionVal.length > 0) {
if ($(':checkbox.' + elem.classList[0] + ":checked").length <= param.max) {
$('#Hobbies-error').empty().append("Select Any Hobbie's checkbox").show();
return false;
}
} else {
$('#Hobbies-error').empty().append("Select a Product").show();
return false;
}
}
$('#Hobbies-error').empty().hide();
return true;
});
$(function () {
// build the dynamic rules....
var myRules = {};
var myMessages = {};
$(':checkbox.hobbycls').each(function (index, element) {
myRules[element.name] = {
checkboxMaxIfiPodNotSelected: {
max: 0,
selEleiSiPod: '#SelectedProductId option:selected'
}
};
myMessages[element.name] = {
checkboxMaxIfiPodNotSelected: function(params, element) {
// it's not usefull to return a true error message because I used a div
// but this is up to you how to manage and place the errors
return '';
}
};
});
// use the rules and messages with validator...
validator = $('form').validate({
rules: myRules,
messages: myMessages,
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
});