Show validation error messages for radio buttons alongside images in a single row

Within a div, I have placed three radio buttons with images inline. My goal is to show a validation message using bootstrap when the submit button is clicked and there is no user input.

I attempted to add another div after the radio buttons with the class "invalid-feedback" but the message failed to display.

<div id="mb">
    <input type="radio" id="h" value="hancock" name="mb" required>
    <label for="h"><img src="static/hancock.jpg" class="img-thumbnail" alt="hancock"></label>
    <input type="radio" id="s" value="shirahoshi" name="mb" required>
    <label for="s"><img src="static/shirahoshi.png" class="img-thumbnail" alt="shirahoshi"></label>
    <input type="radio" id="n" value="nami" name="mb" required>
    <label for="n"><img src="static/nami.jpeg" class="img-thumbnail" alt="nami"></label>
    <div class="invalid-feedback">Please select one option!</div>
</div>

The invalid feedback text was not displayed as intended.

Edit: For code snippet see https://jsfiddle.net/uv51r3jw/5/. I used the novalidate attribute of form to disable default validation.

Answer №1

Enhanced the Javascript validation by adding three lines of code to display invalid feedback when there is no selection and applied styling to images.

        // Example starter JavaScript for disabling form submissions if there are invalid fields
        (function () {
            'use strict';
            window.addEventListener('load', function () {
                // Fetch all the forms we want to apply custom Bootstrap validation styles to
                var forms = document.getElementsByClassName('needs-validation');
                // Loop over them and prevent submission
                var validation = Array.prototype.filter.call(forms, function (form) {
                    form.addEventListener('submit', function (event) {
                        if (form.checkValidity() === false) {
                            if ($('input.Check[name=mb]:checked').length < 1) {  
                               $(".img-thumbnail").css('outline', '1px solid red');
                               $(".invalid-feedback").show();
            }
                            event.preventDefault();
                            event.stopPropagation();
                        }
                        form.classList.add('was-validated');
                    }, false);
                });
            }, false);
        })();

   
   img
    {
        height:100px;
        width:100px;
        object-fit: cover;  
    }  
<html>

<head>
    
    <meta name="viewport" content="initial-scale=1, width=device-width">
    <!-- http://getbootstrap.com/docs/4.1/ -->
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
    <title>snippet</title>
</head>

<body>
    <form action="#" class="needs-validation" novalidate>
        <div id="mb">
            <input type="radio" id="h" value="hancock" name="mb" required>
            <label for="h"><img src="https://images.pexels.com/photos/45201/kitty-cat-kitten-pet-45201.jpeg?auto=format%2Ccompress&cs=tinysrgb&dpr=1&w=500" class="img-thumbnail" alt="h"></label>
            <input type="radio" id="s" value="shirahoshi" name="mb" required>
            <label for="s"><img src="https://images.pexels.com/photos/45201/kitty-cat-kitten-pet-45201.jpeg?auto=format%2Ccompress&cs=tinysrgb&dpr=1&w=500" class="img-thumbnail" alt="s"></label>
            <input type="radio" id="n" value="nami" name="mb" required>
            <label for="n"><img src="https://images.pexels.com/photos/45201/kitty-cat-kitten-pet-45201.jpeg?auto=format%2Ccompress&cs=tinysrgb&dpr=1&w=500" class="img-thumbnail" alt="n"></label>
            <div class="invalid-feedback">Pick One!</div>
        </div>
        <button class="btn btn-primary" type="submit" style="margin-left:11px">Submit</button>
    </form>
    
</body>

</html>

Answer №2

let checkedValue = $("input[name='mb']:checked").val();
if (typeof checkedValue === 'undefined') {
  $('.invalid-feedback').show();
} else {
  $('.invalid-feedback').hide();
}

This could be a solution 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

I am having trouble with my scroll reveal effects on JavaScript, how can I troubleshoot and fix the issue?

I'm currently making updates to my portfolio website, but for some reason, the scroll reveal animation has suddenly stopped working. I made a few edits and now it seems to be broken. /*===== SCROLL REVEAL ANIMATION =====*/ const sr = ScrollReveal({ ...

Is the form being submitted with the href attribute?

Does this code ensure security? <form id="form-id"> <input type='text' name='name'> <input type='submit' value='Go' name='Go'/></form> <a href="#" onclick="docume ...

What is the best way to add a gradient background image to a container that also has margins?

I am currently working on a push menu that shifts the main content container by adding margin-left to it. I am aiming to achieve a background image effect similar to what is seen on . Here is the progress I have made so far in my codepen: https://codepen ...

The sticky navigation and scroll to top features both function perfectly on their own, but when used simultaneously, they do not work

I'm facing an issue with two scripts on my website - when they are separate, they work perfectly fine but together, they don't seem to function properly. What could I be missing here? Script 1: window.onscroll = function() {myFunction()}; var n ...

The website does not support the zoom out or scrolling features on iOS devices

A portion of our website has been optimized for mobile devices, however, we have decided to direct iPhone users to the desktop version when accessing the Blogs section (all PHP content) at this time. While this functions properly on an iPad, we have encou ...

Get a polished look using HTML and CSS exclusively

Allow me to illustrate what I am intending to accomplish with an example. div{ width:100px;height:100px; border:3px solid #900; border-radius:0px 0px 140px 0px; } <div></div> I am seeking a method to ...

Submitting a jQuery Userlike form will not result in a page change

I'm facing a challenge with posting a form without the page refreshing. Despite various suggestions on SO, none of the methods seem to work for my specific case. The use of jQuery's ajax or post APIs is not an option as they change the encoding ...

Updating the Hero Image

Scenario: In my project directory, under Product -> src -> static -> ostatic [ there are two folders named css and images ] -> images -> where all the images can be found. I am using bootstrap and attempting to set a background-image for j ...

Automatically selecting and fetching checkbox values using JavaScript

I was struggling with coding a function that involved generating checkboxes using JavaScript. My goal is to automatically select the elements "March" and "September" from the array target[] and display them as checked in the text area. So, "March" and "Se ...

Allow the div to break out of the overflow: hidden property without disrupting the overall page layout

Currently, I am attempting to separate a child element from its parent that has overflow: hidden applied. The main reason for restricting the dimensions of the parent is for a JavaScript workaround. I have experimented with positioning the child element, ...

Steps for deactivating dropdown when choosing either the first or second dropdown in reverse

My setup includes 2 dropdown menus. These are being populated with product codes (1st dropdown) and product names (2nd dropdown). I am in need of a functionality that allows me to disable one dropdown based on the selection made in the other. For instanc ...

Tips for showing data from Ajax responses on an HTML page

In my code, there are two JavaScript functions: The function fetch_items is responsible for returning data in the form of stringvalue. On the other hand, the function extract_items($arr) passes values to the fetch_items function. function fetch_items ...

Combine various canvases into a single one (for exporting purposes) with pure Javascript

I'm currently faced with a unique challenge involving the creation of around 200 canvases, each showcasing an image captured from the user's webcam as part of an experimentation process for the "photo finish" technique. My task now is to export ...

Issues with jQuery animate not functioning properly when triggered on scroll position

I found a solution on Stack Overflow at this link, but I'm having trouble implementing it properly. The idea is to make an element change opacity from 0 to 1 when the page is scrolled to it, but it's not working as expected. The element is locat ...

Tips for automatically collapsing the Bootstrap 4 Sidebar on smaller devices

I am currently working on some code and have successfully hidden the sidebar using a collapse button. However, I am looking to make it collapse only for small devices, similar to how the bootstrap navbar functions. <link href="https://stackpath.boots ...

What is the process for implementing a grid with 5 columns on larger screens and 2 columns on smaller screens using reactjs?

I am currently working on building a Grid using material UI and reactJs. I found the guidelines on this link https://mui.com/system/react-grid/. However, there seems to be an issue with creating 5 columns in the grid. I attempted to create a custom grid ...

Verify whether the value is in the negative range and implement CSS styling in React JS

I have been developing a ReactJS website where I utilize Axios to fetch prices from an API. After successfully implementing this feature, I am now looking for a way to visually indicate if the 24-hour change percentage is positive by showing it in green, a ...

ASP.NET ensures that the entire page is validated by the form

Is it possible to validate only a specific part of the form instead of the entire page? Currently, when I try to validate textboxes on the page, the validation is applied to all textboxes. Here are more details: https://i.stack.imgur.com/eowMh.png The c ...

Substitute all instances of <table> with <div> tags, making sure to include specifications for

Currently, I find myself immersed in a project that relies heavily on tables, which isn't exactly ideal but is what the marketing department insists upon... To tackle this issue, I have implemented jQuery to convert all tables into DIVs, and so far, ...

Ways to prevent image toggling when the mouse moves out of it or when the hover effect stops

I'm looking to toggle between two images on mouseover/hover and stop the toggling when hovering stops. Here is the HTML code I have: <div class="fader"> <img src="image1" /> <img src="image2" /> </div> This is the JQuery ...