Tom
Tom

Reputation: 21

jQuery addClass as Basis of Form Validation

I am developing a form with a large number of fields and dynamic properties. The basis of validation of required fields is based upon the inputs being assigned a class="req".

<input type="text" name="fieldname" class="req">

Validation function is run when the field changes:

$('.req').change (validate);

The validation is functional for all inputs which have the class hardcoded. However, based upon the selection of a radio, a set of about 12 fields becomes required. To accomplish this I am using addClass('req'). For these dynamically added field classes, validation is not run.

$("input:radio[name=second_owner]").click (function () {
 $('#owner2').hide();
 if ($(this).attr('id') == 'second_owner') {
  $('#owner2').show();
  $('input').each (function () {
   if ($(this).attr('name').indexOf('owner_2') >= 0) {
    $(this).addClass('req');
//  alert ($(this).attr('class'));
   }
  });
 }
});

The alert (when enabled) shows that the class has been assigned but the validation does not run when the fields are changed. I am assuming that the array of required fields must be reloaded in some way in order for this to work.

Any idea of what I am doing wrong?

Upvotes: 0

Views: 82

Answers (2)

Borgboy
Borgboy

Reputation: 670

Tom,

I'm in total agreement with Christian on this but I had some thoughts that might help you in structuring your form.

Instead of using a class 'reg', could you potentially use the disabled state of the additional elements? You had mentioned that 12 fields become required depending on the state of a checkbox or radio button. You could potentially do something like:

$('#my_checkbox').change(
    function(event) {
        if ($('#my_checkbox').prop('selected')) {
            // enable 12 fields here
        } else {
            // disable 12 fields here
        }
    }
);

Instead of just $('input'), you could do something more complex in your selector, such as:

$(':input:not(:disabled))')...

You may also want to consider some type of Form Manager to help you, especially if you have a large set of inputs. This one comes to mind: http://borgboyone.github.io/jquery-form-manager/. There are others out there as well.

A

Upvotes: 1

Christian
Christian

Reputation: 19740

$('.req').change(validate) only binds the change event to elements that have the .req class at the time of execution. This means if you add the .req class to elements after you've called $('.req').change(validate), the change event will not be bound to those elements.

You have 2 options. You can either bind the change events to the element after you've added the .req class, for example:

$(this).addClass('req').change(validate);

Or you can use event delegation. Using jQuery.on(), you can bind the event to a parent element and pass in the optional child selector:

$('body').on('change', '.req', validate);

Replace body with a more suitable parent.

Upvotes: 0

Related Questions