The issue of Bootstrap form validation not functioning properly within a table containing a large checkbox

Currently utilizing Bootstrap version 5.3.3, I have the following structure established to create a large checkbox:

.form-check-input[type=checkbox].big-checkbox {
  transform: scale(3);
  margin: 1.5rem;
  border-radius: 0;
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="23414c4c57505751425363160d100d10">[email protected]</a>/dist/css/bootstrap.min.css" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">

<!-- Table and checkbox inside it without validation -->
<table>
  <tr>
    <td>
      <input type="checkbox" id="exampleOne" name="exampleOne" 
              class="form-check-input big-checkbox"
              checked
              >
    </td>
    <td>
      <label class="form-check-label" for="exampleOne">
        This checkbox does not have validation
      </label>
    </td>
  </tr>
</table>

<!-- Turn this into table with same layout and working validation feedback -->
<form id="form" novalidate>
  <div class="form-check mt-4 mb-3">
    <input type="checkbox" id="exampleTwo" name="exampleTwo"
           class="form-check-input big-checkbox"
           required
           >
    <label class="form-check-label" for="exampleTwo">
      This checkbox has validation 
      <a href="#" data-bs-toggle="modal" 
         data-bs-target="#universalModal"
         data-modal-id="testModal" 
         class="test-link"
         >
        Test link
      </a>
    </label>
    <div class="invalid-feedback">I am a red invalid feedback text.</div>
  </div>
</form>

In order to make the lower checkbox function similarly to the upper one while incorporating Bootstrap's form validation, adjustments need to be made. Utilizing a table layout like below:

<table>
  <tr>
    <td>
      <input type="checkbox" id="exampleTwo" name="exampleTwo"
              class="form-check-input big-checkbox"
              required
              >
    </td>
    <td>
      <label class="form-check-label" for="exampleTwo">
        This checkbox has validation 
        <a href="#" data-bs-toggle="modal" data-bs-target="#universalModal"
           data-modal-id="testModal" class="test-link"
           >
          Test link
        </a>
      </label>
      <div class="invalid-feedback">
        I am a red invalid feedback text.
      </div>
    </td>
  </tr>
</table>

When the large checkbox is invalid, it visually changes color but the label remains unchanged, and the invalid-feedback message does not display. The reason for this discrepancy is due to the separation of the input field, label, and feedback message within different cells of the table.
To ensure proper form validation functionality, all elements should ideally reside within the same parent element. Applying the 'big-checkbox' class in a non-table format can also cause appearance issues.

If you encountered this scenario, how would you address it to maintain consistent form validation behavior as expected within the Bootstrap framework?

Answer №1

Looks like you'll need to manually add validation feedback in this case. You're spot on about the styling being dependent on the element positions, as they should be subsequent-siblings.

You can try customizing the default Bootstrap form controls to resemble a table, or implement manual validation using JavaScript. Make sure to handle checking the checkbox, adding validation classes, and monitoring checkbox changes for all form controls accordingly.

function toggler(el, add) {
  if (add) {
    label.classList.add('invalid-feedback', 'd-block');
  } else {
    label.classList.remove('invalid-feedback', 'd-block');
  }
}

checkBox.addEventListener('change', (e) => {
  if (e.target.validity.valid) {
    toggler(e.target, false);
  } else {
    toggler(e.target, true);
  }
});

Check out the demo below:

.as-console-wrapper { max-height: 50px !important; bottom: 0; }
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <link href="https://cdn.jsdelivr.net/npm/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" />
  <title>Bootstrap Example</title>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
  <style>
    .form-check-input[type=checkbox].big-checkbox {
      transform: scale(3);
      margin: 1.5rem;
      border-radius: 0;
    }
  </style>
</head>

<body class="p-3 m-0 border-0 bd-example m-0 border-0">
  <form class="row g-3" novalidate="" id="myForm">
    <table>
      <tr class="big-checkbox-cont">
        <td>
          <input type="checkbox" id="exampleOne" name="exampleOne" class="form-check-input big-checkbox" required>
        </td>
        <td>
          <label class="form-check-label" for="exampleOne">
              This checkbox does not have validation
            </label>
        </td>
      </tr>
    </table>

    <div class="col-12">
      <button class="btn btn-primary mt-2" type="submit">Submit form</button>
    </div>
  </form>

  <script>
    const checkBoxCont = document.querySelector('.big-checkbox-cont');
    const checkBox = checkBoxCont.querySelector('input');
    const label = checkBoxCont.querySelector('label');

    function toggler(el, add) {
      if (add) {
        label.classList.add('invalid-feedback', 'd-block');
      } else {
        label.classList.remove('invalid-feedback', 'd-block');
      }
    }

    checkBox.addEventListener('change', (e) => {
      if (e.target.validity.valid) {
        toggler(e.target, false);
      } else {
        toggler(e.target, true);
      }
    });

    document.querySelector('#myForm').addEventListener('submit', (e) => {
      e.preventDefault();

      const form = e.target;

      if (form.checkValidity()) {
        console.log('form valid');
      } else {
        console.log('form not valid');
        form.classList.add('was-validated');

        if (!checkBox.validity.valid) {
          toggler(e.target, true);
        }
      }
    });
  </script>

  <!-- End Example Code -->
</body>

</html>

Answer №2

This particular issue is quite uncommon, but fear not, there is a straightforward solution at hand. Bootstrap, being a CSS library, may sometimes clash with custom styles, leading to minor complications.

In your specific scenario, all configurations seem to be in order; however, the form-check class within Bootstrap introduces default padding that is causing the hiccup. To address this, simply incorporate the p-0 class (to eliminate the padding) and make necessary adjustments for alignment.

Let me provide you with an illustrative example of how to refine your code:

Your original code snippet:

<div class="form-check mt-4 mb-3">

The enhanced code snippet:

<div class="form-check mt-4 mb-3 p-0 d-inline-flex align-items-center">

In the upgraded version of the code, I have included the p-0 element to eradicate the padding, and utilized d-inline-flex align-items-center for centralized alignment of elements.

I trust this adjustment will prove effective for you :)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Setting the width to auto, height to 100, and using overflow hidden does not produce the desired result

In my design, I have two sets of images displayed below: https://i.sstatic.net/pQytw.jpg Both sets of images have the exact same code. The only difference between the images in the first and second set is their dimensions. I aim to make all image blocks ...

Selenium Timeout Error: Locator Not Found

Once again, I am struggling with the locator and trying to figure out the correct syntax and code. Here is the code I was attempting to execute: wait.until(EC.presence_of_element_located((By.XPATH, "//div[@class='col-xs-6']//input[@class=&a ...

The Salvattore grid became unresponsive and malfunctioned as soon as AngularJS was integrated

After incorporating AngularJS into my project, Salvatore grid suddenly ceased to function and stopped rendering properly. I am interested in utilizing the ng-repeat feature to iterate through all items and showcase them within the Salvatore grid layout. ...

What benefits do unordered lists <ul>s offer in terms of SEO, accessibility, and beyond for website navigation?

When considering SEO and accessibility, is using <ul> tags a beneficial method for creating straightforward navigation menus? For example, I typically test all my websites with Lynx to ensure they are accessible, and it appears that <ul> tags ...

Instructions for submitting a form to an HTML page in Django

I'm currently working on sending a form to an HTML file using Django. Here is the form I'm working with: from django import forms class contactForm(forms.Form): name = forms.CharField(required=False, max_length=100,help_text='100 character ...

Receive a login submission request from a website

I need help with programmatically logging into a site using Java. I already have the username and password. For example, let's take this site: The code snippet is as shown below: ... HttpPost httpost = new HttpPost("The URL that I require"); List & ...

Simple steps to increase the gap between columns in Bootstrap 4

I created a container with 3 columns using Bootstrap 4: <section id="features"> <div class="container-fluid"> <div class="row justify-content-around"> <div class="col-lg-4 col-md-12 "> <i class="fa ...

Ways to retrieve the child number using JavaScript or PHP

Is there a way to retrieve the child number upon clicking? View screenshot For example, when I click on the X button, I want to remove that specific element. However, this action should only apply to item n2. In order to achieve this, I need to determine ...

Wheel of fortune - The chosen option does not align with the indicator

I am looking to create a game similar to a "Spinning Wheel" where users can select three possible outcomes and then spin the wheel. If any of the chosen three options appears when the wheel stops, the user wins. In the demo provided below, you may notice ...

The lovely border image vanished mysteriously from Safari on both OS and iOS

My border image is no longer appearing in Safari on OS and iOS. I am using Safari 10 on my Mac and the latest version of iOS on my iPad and iPhone. However, it still displays correctly in Firefox. You can view the website URL here: #sidebar .inner{ bor ...

Is it possible to configure mui v5 to display class names without the css-xxx prefix?

Working with mui has truly been a delightful experience. Each developer seems to have their own unique approach when it comes to styling and layout in react. The flexibility provided by mui must present quite the challenge for library developers. In custo ...

Unusual alignment glitch

Just starting out with HTML and CSS as I build my very first website, I've encountered a baffling alignment and positioning issue that has left me scratching my head. Any help in shedding light on this mystery would be greatly appreciated. To better ...

What steps should be taken to populate a grid row if a certain div element is not present?

I am currently using tailwindcss and have this specific HTML code snippet: REPL: https://play.tailwindcss.com/L8McFjGBVC <div class="grid grid-cols-12"> <div class="col-span-4 bg-red-300">1</div> <div class=&qu ...

Could Flexbox CSS be used to create a responsive layout like this?

Appreciate your help in advance. I am facing a challenge with the current layout. <article> <section class="content">1</section> <aside class="ads">2</aside> <section class="comments">3</section> < ...

Struggling to achieve full height for div content between header and footer using Bootstrap 4?

This post may seem similar to others, but it's not. Please read carefully. I am looking to make the main container (<main role="main" class="container">) full-height between the header and footer using Bootstrap 4. Here is my HTML code: // I ...

How can we develop play buttons for Facebook timelines similar to those found on Spotify?

Is it possible to create an HTML5 player that can be embedded on Facebook timelines, similar to the way Spotify has special privileges as a Facebook partner? I'm looking to provide a list of play buttons that, when clicked, will play songs sequentiall ...

Tips for Implementing CSS Styles on Ruby on Rails HTML Pages

Just starting out with RoR and trying to customize my form with CSS classes. Here's what I have so far: <%= form_tag :action => 'create' do %> <p><label for = "name">Name</label>: <%= text_field ...

Even after setting a value to an HTML input field from the C# code behind, any modifications to the text are not being displayed

My form consists of input fields with the attributes type="text" and runat="server" to enable the code behind to access it. Users can input data and later edit the same data if selected from a list. However, after populating the form for editing and making ...

Discovering a locator based on the initial portion of its value

Here's a piece of code that is used to click on a specific locator: await page.locator('#react-select-4-option-0').click(); Is there a way to click on a locator based on only the initial part of the code, like this: await page.locator(&apos ...

Conceal table rows with JQuery in html

I need assistance in hiding a row in an HTML Table that contains a value of 0.00 in the third column. I've attempted using JQuery and CSS, but so far no success. Below is the code snippet: <%@ page language="java" contentType="text/html; charset= ...