hmd hmd - 20 days ago 8
Javascript Question

jQuery Validation based on Next Prev values

I have ran into this problem where I am specifying a Quanitity by both Units and Price. If Units is given, price must also be supplied and if price is given, Units must also be supplied. But they are both blank, then it is ok.

+----------+-------+
| Quantity | Units |
+----------+-------+
| | |
+----------+-------+


I have used the following code to check this condition and it does work for the first instance of the classes but not the proceeding ones.

$(".Quantity").rules("add",{
required:function(element){
return $(".Quantity").next('input').val() > 0;

},
});

$(".Units").rules("add",{
required:function(element){
return $(".Units").prev('input').val() > 0;

},
});


So basically it check only the first value of occurance and not the rest. What I want is it go through complete page and compare prev next value of each occurance. In my case, data is arranged in table and each cell contains Quantity and Price input boxes which I want to retrieve by prev next. but it is not working.

Here is codepen demo. Note that I am using bootstrap dialog as well in the example which shows total number of errors and again it stops at the first instances of the class, not showing all errors because I am using class based rules. Any help would be appreciated.

hmd hmd
Answer

Answering it myself. I had to use the following code to fix my issue

$('.Units').each(function () {
    $(this).rules("add", {
        onkeyup: false,
        required: function (element) {
            return element.nextElementSibling.nextElementSibling.value > 0 ? true : false;
        },
    })
});

$('.Cost').each(function () {
    $(this).rules("add", {
        required: function (element) {
            return element.previousElementSibling.previousElementSibling.value > 0 ? true : false;
        },
    })
});

The actual code I used is more complicated where prev and next values were dependent on each other.

Comments