Ways to confirm the validation of radio buttons in a form and implement CSS

I am having trouble adding validation to a form with radio buttons displayed as labels. I want to show a red border around the radios/labels or outer div when a radio button hasn't been checked before the user submits the form.

I have attempted this in two different ways, but neither method seems to be working. Here are my attempts:

First attempt...

function validate() {
  var label = document.getElementById('title');
  if (document.querySelectorAll('input[type="radio"]:checked').length === 0) {
    $("#title").css('border', '3px red solid');
    } else {
      $("#title").css('border', '');
  }
}
.error {
  border: 3px solid red !important;
}




input[type=radio] {
    display:none;
}

input[type=radio] + label:hover {
  cursor:pointer;
  border:1px solid royalblue !important;
}

/*
  Change the look'n'feel of labels (which are adjacent to radiobuttons).
  Add some margin, padding to label
*/
input[type=radio] + label {
    font-size:14px;
    text-align:center;
    display:inline-block;
    margin:12px;
    width:24%;
    border:1px solid black !important;
    border-radius:4px;
    vertical-align:top;
}
/*
 Change background color for label next to checked radio button
 to make it look like highlighted button
*/
input[type=radio]:checked + label { 
  background-image: none;
  border:2px solid royalblue !important;
  opacity:0.9;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<form>

  <input type="radio" id="title" required>
  <label class="tg" for="title">
    test
  </label>
  <input type="radio" id="title2" required>
  <label class="tg" for="title2">
    test
  </label>
  <input type="radio" id="title3" required>
  <label class="tg" for="title3">
    test
  </label>
  <input type="submit" onclick="validate()">
</form>

Here is my second attempt...

function validateForm() {
  var radios = document.getElementsByName("group_1", "group_2");
...
input[type=radio] {
  display: none;
}

input[type=radio]+label {
  text-align: center;
...
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<form name="form1" action="#" onsubmit="return validateForm()" method="post">
...
</form>

Answer №1

Both tries came close to the solution.

The following issues are causing your code not to work:

Try 1:

  • In order to prevent a submit button from working, the onclick function must return a value. It cannot be the default return (undefined); it must be explicitly set to a specific value. For example, function foo() { return false } will prevent the submit action.
  • The use of the id attribute needs to be unique (You have repeated "title")

Try 2:

  • Similar id problems as in Try 1 (multiple occurrences of "s2")
  • You are attempting to set the border of the label for a radio button, but the CSS selector is selecting the radio button itself instead of the label.

Here is a corrected version of Try 2:

function validateGroups() {
  let valid = true
  const groups = [ "group_1", "group_2" ];
  for (group of groups) {
    radios = $(`input[name=${group}]`)
    if ($(`input[name=${group}]:checked`).length === 0)  {
      for (radio of radios) {
        $(radio).next('label').css('border', '2px solid red');
      }
      valid = false;
    }
  }
  return valid;
}

function validateForm(form) {
  if (!validateGroups()) {
    event.preventDefault()
    return false;
  }
  return true;
}
input[type=radio] {
  display: none;
}

input[type=radio]+label {
  text-align: center;
  display: inline-block;
  margin: 6px;
  width: 24%;
  border: 2px solid black;
  border-radius: 4px;
  vertical-align: top;
}

input[type=radio]:checked+label {
  background-image: none;
  border: 2px solid royalblue !important;
  opacity: 0.9;
}

.error {
  border: 4px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="form1" action="#" method="post" onsubmit="return validateForm(this)">
  <input type="radio" id="s1_1" name="group_1" value="1" />
  <label for="s1_1">Option 1</label>
  <br />
  <input type="radio" id="s1_2" name="group_1" value="2" />
  <label for="s1_2">Option 2</label>
  <br />
  <input type="radio" id="s2_1" name="group_2" value="1" />
  <label for="s2_1">Option 1a</label>
  <br />
  <input type="radio" id="s2_2" name="group_2" value="2" />
  <label for="s2_2">Option 2a</label>
  <input type="submit" value="Submit"><br />
</form>

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

Function wrapper intended for axios

How can I create a wrapper function for axios? I am looking to create a function that can return axios, allowing for easy substitution with another fetch API in the future. This is what I have attempted so far: import axios from 'axios' expor ...

Tips for iterating through an array of images and displaying them in a React component

I am working on a project in my react app where I have 5 images that I want to cycle through indefinitely. The goal is to create an animation where a light bar appears to be constantly moving. The shifting dot in each image will give the illusion of movem ...

Conceal a column within a nested HTML table

I am facing a challenge with a nested table column structure: My goal is to hide specific columns based on their index within the table. Can someone explain the concept behind achieving this? I am unsure of how to get started on this task. <table clas ...

The Express application fails to receive a response from a Mongodb query function

In my current project, I am implementing a simple API Key authentication system. The main goal is to validate the provided key against the user's input. There is a separate file containing a function that queries the database and returns either true/ ...

Efficiently styling table Spans with styled components in React

Can anyone help me with a frustrating CSS problem I'm facing? I am trying to render these tags as spans, but they are not separating properly as shown in the image below. They appear stuck together and I can't figure out why. I am using styled co ...

Having trouble making changes to MUI TextFields once they've been filled in with data from an

My goal is to make MUI TextFields editable even after they have been filled with data from an API. The TextFields are getting populated successfully. I attempted using an onChange function, but it only allowed one additional character to be entered befor ...

Is it possible for individuals on the local network to view the webpage?

Recently, I developed a login page in HTML that prompts users for their username and password. The information is then sent to ABC.php, and upon successful authentication, they are redirected to another website. To make this work, I set up a xampp server. ...

Using the React Hook useCallback with no dependencies

Is it beneficial to utilize useCallback without dependencies for straightforward event handlers? Take, for instance: const MyComponent = React.memo(() => { const handleClick = useCallback(() => { console.log('clicked'); }, []); ...

Sending a CSS class name to a component using Next.js

I am currently in the process of transitioning from a plain ReactJS project to NextJS and I have a question. One aspect that is confusing me is how to effectively utilize CSS within NextJS. The issue I am facing involves a Button component that receives ...

Clicking on text within a DIV using jQuery

How can I use jQuery to show an "alert" when text inside a DIV is clicked, excluding images and other tags? The texts are contained within various DIVs along with images and tags. Is there a way to achieve this using jQuery? Check out the jsFiddle example ...

Tips for enhancing the contents of a single card within a react-bootstrap accordion

Currently, I am facing an issue with my columns expanding all cards at once when utilizing react-bootstrap accordion. My goal is to have each card expand individually upon clicking on its respective link. However, I am encountering difficulties in implem ...

What is the best way to retrieve the current value of a range slider?

Having some trouble with the "angular-ranger" directive that I loaded from a repository. Can anyone assist me in figuring out how to retrieve the current value of the range slider? Any guidance or suggestions would be greatly appreciated! For reference, ...

ASP.NET MVC - AjaxContext is a powerful feature provided by the

I recently attempted to delve into the AjaxContext utilized by ASP.NET-MVC in scenarios such as Ajax Actionlinks and their clientside functions like onSuccess and onComplete. However, I must admit that I found it quite confusing... Is there any documentati ...

Switching the keyboard language on the client side of programming languages

I'm interested in altering the keyboard language when an input element changes. Is it possible to modify the keyboard language using client-side programming languages? And specifically, can JavaScript be used to change the keyboard language? ...

What is the method for accessing the value of variable "a" in the following code?

request(target, function (err, resp, body) { $ = cheerio.load(body); links = $('a'); $(links).each(function (i, link) { if ($(link).text().match('worker')) { var a = $(link).attr('href').toStri ...

What is the best way to automatically increase the value of another column in SQL when the primary key is set to auto

In my database, I currently have a table storing customer details. I am looking to introduce a new column that will provide either existing or new customers with a unique auto-incremented ID for identification purposes. Additionally, I require a primary ke ...

Looking for assistance with converting a basic script into a Joomla 2.5 module and resolving issues with Java integration

I'm having issues with my code in Joomla 2.5. It seems like the Java function is not functioning properly within Joomla. Can someone assist me with troubleshooting this problem? mod_mw_pop_social_traffic.php <?php defined( '_JEXEC' ) or ...

How can I parse JSON in React using the Parse function?

I am currently working with three list components, and when I click on any item in the tree list, it displays the JSON data. However, I would prefer to view it in a parse format rather than JSON. I attempted to use let json = JSON.parse(this.props.node, n ...

Customize arrow direction in AntDVue ant-collapse using simple CSS styling

Is there a way to customize the arrow directions in ant-collapse vue? I recently faced an issue where I couldn't change the arrow directions without using !important (which I try to avoid). Fortunately, we found a workaround for this problem at my wo ...

Retrieve: Type 'string | undefined' does not match the parameter type 'RequestInfo'

When using the fetch function, I encountered an error with the "fetchUrl" argument: Error: Argument of type 'string | undefined' is not assignable to parameter of type 'RequestInfo'. This is the code snippet where the error occurred: ...