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

Customizing Row Background Color in Bootstrap

Currently working on a project www.codepen.io/anon/pen/yMmjZb The problem I am facing is with my 3rd row (the one with the 3 columns) where the background color is bleeding beyond the intended boundary. My suspicion is that it's due to the row span ...

Find the months where two date ranges overlap with the help of date-fns

Is there a way to find the overlapping months between two date intervals using date-fns? const range1 = { start: new Date('2018-01-01'), end: new Date('2019-01-01') } const range2 = { start: new Date('2018-07-03'), end: new D ...

Guide on utilizing multiple ng-apps alongside multiple controllers

Having trouble accessing controller values in different ng-apps? Here's a setup with two ng-apps and their controllers, where you may encounter errors when trying to access the value of one controller in another. Need some assistance with this issue. ...

Nested ui-view is not appearing as expected

I have a query about Angular UI-Router and its ui-views functionality. I am facing an issue where only the ui-view with the name "languages" is displaying, despite declaring three ui-views inside another one. Any assistance in resolving this would be highl ...

Having trouble extracting a value from a JSON object in JavaScript

I am encountering an issue while attempting to extract a specific value nested within a JSON object. The API call response is provided below. var responseData = { "statusCode": 200, "body": "{\"Errors\":\"\",\"Message\":n ...

Is there a way to display the avatar image outside of the drawer in MUI ReactJS?

Currently, I am attempting to display the avatar image with a curved effect outside the border line of the sidebar. I have referenced the persistent drawer from MUI v5 for inspiration. You can view an example here: the codesandbox link The desired outcom ...

Difficulty in showcasing error on the website with JavaScript

I have recently developed a webpage that includes several input boxes and a submit button within a form as shown below: <form action="" method="post" name="password"> Upon clicking the submit button, a JavaScript function is triggered to validate i ...

Repetitive data in a list with AngularJS

There's probably a simple solution to this: I have some data in a controller, and depending on whether an item is selected or not, it should display different HTML. If the item is selected, the HTML should be: <li> <a href="#"><s ...

Sharing state between two functions in React using Hooks

Coming from a background in Vue, I am struggling to comprehend how to conditionally show something when the HTML is fragmented into different parts. Imagine having this structure: import React, { useState } from "react"; const [mobileNavOpen, setMobi ...

What steps should I take to resolve the textarea border bottom CSS effect?

My simple border bottom animation is working fine with a basic input element, but it's not functioning properly when used with a textarea. (If using JavaScript is necessary for a solution, please provide guidance) How can I adjust the height of a te ...

Tips for safeguarding the security of my PHP API when accessed through Ajax using OAuth2

I've developed a cross-origin ajax application that utilizes some personal APIs I created. Now, I'm looking to enhance the security measures so only my application has access to the API. After researching, I came across OAuth2 at OAuth2. I foll ...

How to keep text always locked to the front layer in fabric.js without constantly bringing it to the front

Is it possible to achieve this functionality without using the following methods? canvas.sendBackwards(myObject) canvas.sendToBack(myObject) I am looking to upload multiple images while allowing them to be arranged forward and backward relative to each o ...

Starting the selection process using AngularJS and ng-repeat

My challenge is to have a pre-filled option in a select-box using ng-repeat with AngularJS 1.1.5. However, the select box always starts off with nothing selected and an empty option, which I don't want. It seems to be a side effect of not having anyth ...

Resolving AJAX requests within a loop

I am working with a JSON file that contains widgets {"widgetname": "widget1", "widgetID": "FJRH585fKFJN234NC"} As I iterate through the JSON, I generate HTML for each widget object. $.ajax({ url: "get_json.php", data: {action: "get_widgets", ...

React Virtualized - Blank screen issue occurring because of continuous scrolling through a large list of ITSM items

I am currently working on a lengthy list of items and utilizing the react-virtualized library for this purpose. However, I have encountered an issue that needs addressing. https://i.stack.imgur.com/ROdjp.gif Upon attempting to scroll down for 2 seconds, ...

Script in Javascript halting Internet Explorer's operation

I'm encountering a problem with Internet Explorer freezing due to the following code. This code is part of a project that focuses on handling student grades: var array1 = StudentGradeAreadHugeList(); var nextArrayItem = function() { var grade = ...

Can the keypress event be modified within the Google Chrome browser?

My code is functioning in IE but not in Chrome. I am having issues with the event not changing. Is there a different method for achieving this in Chrome, rather than assigning specific values to the charCode, keyCode, and which variables? You can view my ...

How to Arrange AppBar Elements in Material UI with React

I'm struggling to align the CloseIcon to be at the end of the container using flex-end but I can't seem to locate where to apply that style. import React from 'react'; import { makeStyles, useTheme } from '@material-ui/core/sty ...

jQuery document.ready not triggering on second screen on Android device

Why is jQuery docment.ready not firing on the second screen, but working fine on the first/initial screen? I also have jQuery Mobile included in the html. Could jQuery Mobile be causing document.ready to not work? I've heard that we should use jQuery ...

Retrieving the value of a specific property nested within a JSON object using basic JavaScript

Hey there! Thanks for taking the time to check out my question. I'm diving into JavaScript and I've hit a roadblock trying to solve this particular problem: I'm looking to extract the value of a property nested within a JSON object under a ...