Question

I'm gonna try to keep this one as simple as possible, sorry if it's messy..

I've built (don't ask why) a custom validation for a form on a wordpress site with jQuery/JS. The generall idea is I have an array with ID's of input fields that it should check. So the list goes:

toValidate=new Array(); 
toValidate[0]="#name";       
toValidate[1]="#location";
toValidate[2]="#method";

and it loops them with $.each(toValidate) and then if they're empty gives a popup and does some other stuff like add red borders to the fields. Now all of this works fine. But I have another problem. I have a couple of fields that are always required, but I also have a checkbox, when they check it, a TR is supposed to be removed, that TR has a couple of fields in it that are required IF visible.

Now the problem is that even if I click the checkbox, hence remove the TR, I can't get it to work so that the required fields of that remove TR are no longer required. I've tried multiple ways but keep getting different problems depending on what solution I try.

What I've tried for an example is to change the array so that if they check the box, it removes a couple of the array objects (those that are in the row that is removed). But it doesn't work, it just acts as if they're still there.

Sorry for making this long but what I'm trying to ask is what would be best practice to do here? What would YOU do? I don't want code, just a general idea of how I should plan it this as I'm stuck..

Edit: I forgot to mention, my way with the array may be a worthless idea too, so any ideas on how to improve it and make it work are appreciated.

Was it helpful?

Solution

Rather than adding/removing visibility in javascript, do it in css. It'll simplify your selectors when validating.

css:

table tr.ignore {
  visibility: hidden;
}

javascript:

$('input.hide_thing').click(function() {
  $('tr.whatever_tr').toggleClass('ignore', !$(this).checked)
});

validator:

$('tr:not(.ignore)').validate();

OTHER TIPS

You could preface your validation by checking if the element is visible.

$.each(toValidate, function(index, element) {

    if (!$(element).is(':visible')) return;

    // ... proceed to validate
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top