I have a table with courses. The user that is currently logged in can mark these courses as attended and unattended. There can be multiple rows selected.

The logic for this row selecting looks like this:

  • It's not possible to select courses which you have attended when there are unattended courses selected. This works vica versa.
  • When a unattended course is selected, a button for attending this course will be enabled.
  • When a attended course is selected, a button for unattending this course will be enabled.
  • For every row, the checkbox which is inside the table will be checked.

What I currently ended up with is this:

 * The form for handling requests
 * @type {jQuery|HTMLElement}
const form = $('#attendCourseForm');

 * The buttons for attending a course
 * @type {jQuery|HTMLElement}
const courseFollowButton   = $('#courseFollowButton'),
      courseUnFollowButton = $('#courseUnfollowButton');

 * Selecting rows
form.on('click', 'tbody tr', select);

 * Select the course rows
function select() {
    const $this    = $(this),
          attended = $this.hasClass('attendedCourse'),
          siblings = $this.siblings();

    let toggle = 'table-active',
        button = courseFollowButton;

    // Prevent selecting more types
    if (attended) {
        if (siblings.hasClass('table-active')) {
        toggle = 'table-secondary';
        button = courseUnFollowButton;
    } else if (!attended && siblings.hasClass('table-secondary')) {


    // Toggle the checkbox
    let checkbox = $this.children().last().find('input[type=checkbox]');
    checkbox.prop('checked', $this.hasClass(toggle));

    // Turn buttons on and off
    let hasToggleClass = $this.hasClass(toggle) || siblings.hasClass(toggle);
    button.prop('disabled', !hasToggleClass);

This looks like a mess to me. Can this be done any better?


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.