0

I'm trying to add conditions to some of my fields of my contribution page, where for example, if a checkbox is checked, it should add the required attribute to this field, and then not submit the form if this field is not filled.

My problem is that, if all of the other form fields are correctly filled, the form is still submitted even if the 'required' attribute was added to this text field, and yet i didn't write anything. But if the form fields aren't correctly filled, the form is not submitted, and as the contribution page is reloaded, it seems like the 'required' attribute is now taken into account, and a small alert now pops up if the field is not filled.

Here is the small code i wrote to obtain this behaviour :

CRM.$(function($) {


 var checkbox_1 = $("input[id^='custom_5_7']");
 var other_text = $("input[id^='custom_6']");

 var effectsForOthers = function () {
    if (checkbox_1.is(':checked')) {
        cj("[class^='crm-section helprow-custom_6-section helprow-pre']").css("display", "block");
        cj("[class^='crm-section editrow_custom_6-section form-item']").css("display", "block");
        other_text.attr('required', true);
    }
    else {
        cj("[class^='crm-section helprow-custom_6-section helprow-pre']").css("display", "none");
        cj("[class^='crm-section editrow_custom_6-section form-item']").css("display", "none"); 
        other_text.attr('required', false);
    }
  };


   effectsForOthers();

   checkbox_1.on('change', effectsForOthers);

 });

});

I would be glad if you could help me.

Thanks in advance for all of your suggestions.

  • This is a left-field recommendation, but have you tried using webform_civicrm to get this functionality? I know I am not answering your question directly but thought I'd put it out there. – Zachary Jun 14 at 0:00
  • 1
    I am not fond of using webform_civicrm, as i am using stripe for my contribution, and webform and stripe don't seem to work well together. – Guillaume Sorel Jun 14 at 10:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.