I’m trying to add some classes to my form on submit which indicates which required fields haven’t been addressed.
I have this working for input[type="text"]
, but it doesn’t work for radio options. Upon inspecting the code, it doesn’t even add the error
class to the radio
element?
Demo:
(function ($) {
$('#rsvp form input[type=submit]').click(function(e){
console.log("click");
var data = $('#rsvp form').serialize();
[].slice.call($('#rsvp form input.required')).forEach(function (elem, index) {
$elem = $(elem);
console.log(elem);
if($elem.val().length == 0){
$elem.addClass("error");
} else{
$elem.removeClass("error");
}
});
});
}) (jQuery);
.error{
background: red;
}
.error.input-label:before{
border-color: red;
}
:root {
--green: #9A9E90;
--black: #000000;
}
fieldset{
margin-bottom: 50px;
}
form{
position: relative;
}
input {
width: 100%;
box-sizing: border-box;
background: none;
outline: none;
resize: none;
border: 0;
border-bottom: 2px solid var(--green);
border-left: 2px solid var(--green);
}
input[type=checkbox], input[type=radio] {
position: absolute;
opacity: 0;
}
input[type=submit] {
cursor: pointer;
display: inline-block;
width: fit-content;
color: var(--black);
border: 2px solid var(--green);
padding: 20px 30px;
text-transform: uppercase;
}
.input-label {
display: inline-block;
position: relative;
margin-right: 30px;
padding-left: 25px;
cursor: pointer;
}
.input-label:before, .input-label:after {
content: "";
position: absolute;
top: 50%;
transform: translate(0px, -50%);
left: 0;
}
.input-label:before {
display: block;
width: 15px;
height: 15px;
border: 2px solid var(--green);
}
.input-label:after {
display: none;
width: 9px;
height: 9px;
margin: 3px;
background-color: var(--green);
transform: translate(0px, -82%);
}
input:focus + .input-label:before {
border-color: var(--green);
}
input:checked + .input-label:after {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<div id="rsvp">
<form>
<fieldset>
<span>Attending?</span>
<input class="required" id="attending-yes" type="radio" name="attendance" value="yes" required />
<label class="input-label" for="attending-yes">Yes</label>
<input class="required" id="attending-no" type="radio" name="attendance" value="no" required />
<label class="input-label" for="attending-no">No</label>
</fieldset>
<fieldset>
<input class="required" type="text" name="full_name" placeholder="Your full name*" required />
</fieldset>
<input type="submit" name="submit" value="Send" />
</form>
</div>
2
Answers
You can do it like this to check if the checkbox of a group is checked or not.
You should have an id/Class for "Submit" button and add the click function in the script to add class name for unselected radio buttons/button.
Hope this helps!!