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>