You are viewing limited content. For full access, please sign in.

Question

Question

Javascript Checkbox Require

asked on November 15, 2022

I am trying to make it so when someone fills out a single line name field in a table, the checkbox becomes required. Here is my current attempt at it:

$(document).ready(function () {
  $('.cf-table-block').change(function () {
        $('.tableclass').on('blur', 'input', checkdesc);
    });
 
    function checkdesc() {
    $('.tableclass tbody tr').each(function () {
        if ($(this).find('.nameclass input').val() != "") {
          $(this).find('.checkboxclass input').attr('required', true);
        } else {
          $(this).find('.checkboxclass input').removeAttr('required');
        }
    });
  }
  });

However this keeps happening:


Even if you check all the boxes, it won't let you submit. What am I doing wrong? This logic works for non-checkbox fields so I'm guessing I'm missing something specific to checkboxes.

0 0

Answer

SELECTED ANSWER
replied on November 15, 2022

You are making every single checkbox plus the hidden "other" textbox required.  You need to ensure you are only making the checkboxes required, and excluding the "other" textbox.

Additionally, if you want it to behave the way it does normally with the required option from the Layout page, you need to add the group-required class, which allows it to work when one or more checkboxes are marked, instead of requiring all of them to be marked.

Here's your code, modified to address those two items:

$(document).ready(function () {
  
  $('.cf-table-block').change(function () {
    $('.tableclass').on('blur', 'input', checkdesc);
  });
 
  function checkdesc() {
    $('.tableclass tbody tr').each(function () {
      if ($(this).find('.nameclass input').val() != "") {
        //New version limited to just the input checkboxes, and includes addition of the group-required class.
        $(this).find('.checkboxclass input[type="checkbox"]').attr('required', true).addClass('group-required');
      } else {
        //New version limited to just the input checkboxes, and includes removal of the group-required class.
        $(this).find('.checkboxclass input[type="checkbox"]').removeAttr('required').removeClass('group-required');
      }
    });
  }
  
});

 

2 0

Replies

You are not allowed to reply in this post.
You are not allowed to follow up in this post.

Sign in to reply to this post.