Reputation: 4386
I'm trying to have a dynamically updated min value on one field, depending on input from other fields. Heres my code in short:
$("#new_project").live("click", function() {
switch($('input:radio[name=quality-level]:checked').val()){
case 'average' : ppw = .006;
case 'below-average' : ppw =.004;
case 'good' : ppw = .008;
case 'very-good' : ppw = .016;
}
if ($('#minimum-word-length').val() && $('input:radio[name=quality-level]:checked').val())
{
min_price = $('#minimum-word-length').val() * ppw;
}
$("#new_project, .edit_project").validate({
rules: {
...
"price-per-article": {required: true, number: true, min:min_price},
...
},
errorPlacement: function(error, element) { }
});
});
Min price is set correctly, and updates correctly. That said, for whatever reason, the min value rule doesnt update which i think is because the validate code is only loaded on document load. So I guess is there a way to reload the rules so that the min value changes when then the two necessary fields are filled?
Thanks!
Upvotes: 5
Views: 6645
Reputation: 563
This example gets min year & max year is derived from min:
$(document).ready(function () {
function getMinYear() {
var d = new Date();
var y = parseInt(d.getFullYear());
console.log("Min: " + y);
return y;
}
$("#frmAddCard").validate({
rules : {
year : {
required : true,
number: true,
min: getMinYear(),
max: getMinYear() + 10
}
},
messages : {
year : {
required : "Expiration Date: Please enter valid year (e.g. 2016)",
number : "Expiration Date: Please enter valid year (e.g. 2016)",
min : function (elem) {
var y = getMinYear();
return "Min: Please enter the value between " + y.toString() + " and " + (y + 10).toString();
},
max : function (elem) {
var y = getMinYear() + 10;
return "Max: Please enter the value between " + y.toString() + " and " + (y + 10).toString();
}
}
},
submitHandler : function (form) {
},
invalidHandler : function (event, validator) {
}
});
});
Upvotes: 0
Reputation: 3247
The problem is you're setting up the validate object with the price-per-article on initial load. I'm not familiar with the validate plug-in, but in general, if your properties change for an object real time, you'll want to use a callback function for that property as opposed to setting it's data on load.
So for the price-per-article entry it'd probably look like:
"price-per-article": {
required: true,
number: true,
min: function () { return $('#minimum-word-length').val() * ppw; }
}
Upvotes: 7
Reputation: 933
Instead of having a fixed value for the validation for price-per-article, change it to an anonymous function:
"price-per-article": {
required: true,
number: true,
min: function() { return min_price; }
}
This way the value of min_price is checked every time validation is called.
Upvotes: 1