How do I validate a radio button with JavaScript? - javascript

How do I validate a radio button? I want to make it so that if the user left the radio button unclicked the section background will turn a red colour/color.
Here is the HTML Page
<p id="caption_project">Project Selection
<br/>
<input type="radio" name="f__project" id="in_restaurant" value="restaurant"/>
<label for="in_restaurant">LEGO Project</label>
<br/>
<input type="radio" name="f__project" id="in_humber" value="Humber News"/>
<label for="in_humber">Humber Current Project</label>
<br/>
<input type="radio" name="f__project" id="in_self" value="self-determined"/>
<label for="in_self">Self-determined Project</label>
</p>
So how do I turn the background red when they leave it unchecked?

You need to think of some event the user will fire which you want to trigger the function that makes the background go red. That could be if the user clicks on the next form control. Then when that event fires you test whether they checked any radio buttons. If they did not (!checked) then you set the style attribute of your p element to background:red:
const nextThing = document.querySelector('#next-thing');
const p = document.querySelector('p');
nextThing.addEventListener('click', function(){
const checked = document.querySelector("input[name='f__project']:checked");
if(!checked){
p.setAttribute('style', 'background:red');
}
});
<p id="caption_project">Project Selection
<br/>
<input type="radio" name="f__project" id="in_restaurant" value="restaurant"/>
<label for="in_restaurant">LEGO Project</label>
<br/>
<input type="radio" name="f__project" id="in_humber" value="Humber News"/>
<label for="in_humber">Humber Current Project</label>
<br/>
<input type="radio" name="f__project" id="in_self" value="self-determined"/>
<label for="in_self">Self-determined Project</label>
</p>
<button id='next-thing'>Next form control</button>

Use document.querySelector("input[name='f__project']:checked"). If this returns null, none of the radio buttons were checked, and you can display the red background.
If this is in a <form> you can add the required attribute to the radio buttons. If they try to submit the form without selecting one of them, the browser will display a validation error.

Use document.getElementById('id').checkedthe statement returns True or False.

const checkedRadioButton = document.
querySelector("input[name='f__project']:checked");
if (!checkedRadioButton) {
// No values are selected
} else {
// Some value is selected and the element is stored in checkedRadioButton
}

You can use CSS to manipulate the colour depending on whether the radio input is checked or not.
input[type="radio"] {
display: none;
}
input[type="radio"] + label {
border: 5px solid lightblue;
background-color: lightblue;
cursor: pointer;
display: block;
height: 40px;
width: 200px;
text-align: center;
line-height: 40px;
}
input[type="radio"]:checked + label {
border: 5px solid blue;
background-color: dodgerblue;
}
Or else you can make a Javascript function to check
function checkRadioValidity() {
if(document.getElementById('in_restaurant').checked) {
//change CSS here for the element
}
}

The idea of radio button is that it can not be unchecked.
EDIT:
document.querySelector("input[name='f__project']:checked")
will return element if it is checked

Related

How to fix my Javascript for checkbox questions/answers with feedback?

I need help figuring out how to get each checkbox give back a different modal. I figured if it was fine with showing two modals that I could add another one in but it did not work. I want it to give separate feedback for each answer chosen. So for example if Answer A is chosen, then I want Modal1 for feedback. Same for B but Modal 2. Choice C works as being correct already.
<form id="submit1">
<div id="question1" class="p-body flex-col-left" style="justify-content: flex-start;">
<label>
<input type="checkbox" name="input" value="wrongA" class="question1" data-seen=1>
<span class="lineup">A. Emily should cross through the incorrect information and write in
the correct information.</span>
</label>
<br>
<label>
<input type="checkbox" name="input" value="wrongB" class="question1" data-seen=2>
<span class="lineup">B. Emily does not need to do anything until it is time for her to renew
her license.</span>
</label>
<br>
<label>
<input type="checkbox" name="input" value="right" class="question1" data-seen=0>
<span class="lineup">C. Emily needs to fill out the appropriate paperwork and submit it to
the TDLR. </span>
</label>
<br>
<br>
</div>
<div class="flex-center">
<button type="submit" id="answer" class="modal-button modal-a">Submit</button>
</div>
</form>
<script>
document.getElementById("answer").onclick = validate;
function validate() {
var checkboxes = document.getElementsByName("input");
var checkboxChecked = [];
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked && (checkboxes[i].value === "right")) {
checkboxChecked.push(checkboxes[i]);
}
}
for (var i = 1; i < checkboxes.length; i++) {
if (checkboxes[i].checked && (checkboxes[i].value === "wrongA")) {
checkboxWrongA.push(checkboxes[i]);
}
}
for (var i = 2; i < checkboxes.length; i++) {
if (checkboxes[i].checked && (checkboxes[i].value === "wrongB")) {
checkboxWrongB.push(checkboxes[i]);
}
}
if (checkboxChecked.length === 1) {
const modal1 = document.querySelector('#modal1');
modal1.style.display = 'block'
window.nextBtn.style.display = "block";
window.dropdown.style.display = "block";
window.breadcrumb.style.display = "block";
}
if (checkboxWrongA.length === 1) {
const modal2 = document.querySelector('#modal2');
modal2.style.display = 'block'
}
if (checkboxWrongB.length === 1) {
const modal3 = document.querySelector('#modal3');
modal3.style.display = 'block'
}
}
</script>
Because you mentioned that your users should only choose 1 option, then a set radio buttons would be the way to go. Then we need to evaluate your JS to work with the radio buttons.
First of make sure that each radio has the same name attribute value. This enables us to use the name to get the value from the input that is checked. Allow the value to represent the chosen option. You could use right or wrongA here, but that doesn't say much about which option is chosen, only it's correctness.
<input type="radio" name="answer" value="A">
<input type="radio" name="answer" value="B">
<input type="radio" name="answer" value="C">
Now on the JavaScript side, we can make things simpler. Since you're using a <form> element, I'd suggest that you listen for a submit event on the form to know when you clicked your validate button.
A submit event happens whenever you have <form> with a <button type="submit"> inside of it and click the button. By default the page would reload. We'll need to stop that from happening by preventing the default behavior of the form. (see event.preventDefault()).
We can extract the data from the form using a FormData object. This object does a lot of work for us, for example, figuring out which of our inputs have been checked. With that object, we can ask for the value of the input by using the name of the input. In this case, I used the name: 'answer'.
Because we now use radio inputs, the value can only be either A, B or C. Based on the answer, look for the appropriate modal and show it.
const form = document.querySelector('#question-form');
form.addEventListener('submit', event => {
event.preventDefault();
const formData = new FormData(form);
const answer = formData.get('answer');
if (answer === 'A') {
const modal = document.querySelector('#modal1');
modal.classList.add('show');
} else if (answer === 'B') {
const modal = document.querySelector('#modal2');
modal.classList.add('show');
} else if (answer === 'C') {
const modal = document.querySelector('#modal3');
modal.classList.add('show');
}
});
.modal {
display: none;
position: fixed;
top: 50%;
left: 50%;
translate: -50% -50%;
background: pink;
padding: 50px 100px;
}
.modal.show {
display: block;
}
<form id="question-form">
<div>
<label>
<input type="radio" name="answer" value="A" class="question1" data-seen=1>
<span class="lineup">A. Emily should cross through the incorrect information and write in the correct information.</span>
</label>
</div>
<div>
<label>
<input type="radio" name="answer" value="B" class="question1" data-seen=2>
<span class="lineup">B. Emily does not need to do anything until it is time for her to renew her license.</span>
</label>
</div>
<div>
<label>
<input type="radio" name="answer" value="C" class="question1" data-seen=0>
<span class="lineup">C. Emily needs to fill out the appropriate paperwork and submit it to the TDLR.</span>
</label>
</div>
<button type="submit" class="modal-button modal-a">Submit</button>
</form>
<div id="modal1" class="modal">
Modal 1
</div>
<div id="modal2" class="modal">
Modal 2
</div>
<div id="modal3" class="modal">
Modal 3
</div>
In this example checkboxes are replaced by radio buttons since it looks as if there's only one correct answer (and multiple modals are silly). The modals are <dialog> elements. Also, the "answer" button triggers a "submit" event that's registered to the <form>. The event handler check(e) is designed to leverage control by event delegation. In addition, the HTMLFormElement and HTMLFormControlsCollection interfaces were used to reference the <form> and it's form controls (all <input> in the <form>).
Details are commented in example
/**
* Register the <form> to the "submit" event
* The event handler check(e) is called when a "submit" event is triggered
*/
document.forms.quiz.onsubmit = check;
/**
* The event handler passes the Event object by default
* Prevent the default behavior of <form> during "submit" event
* Collect all HTMLFormControls into a HTMLCollection
* If a one form control with [name="chx"] is .checked...
* ...get the checked radio button's value...
* ...reference the <dialog> with the class of the same value as the
* checked radio button...
* ...then open that <dialog>
*/
function check(e) {
e.preventDefault();
const fc = this.elements;
if (Array.from(fc.rad).some(c => c.checked)) {
const answer = fc.rad.value;
const modal = document.querySelector('.' + answer);
modal.showModal();
}
}
/**
* Collect all .close (buttons) into a NodeList and bind each one to the
* "click" event.
* The event handler close(e) is called when the "click" event is triggered.
*/
document.querySelectorAll(".close").forEach(btn => btn.onclick = close);
/**
* This event handler will close the parent <dialog> of the clicked <button>
*/
function close(e) {
this.closest('dialog').close();
}
html {
font: 300 2ch/1.2 'Segoe UI'
}
body {
min-height: 100vh;
}
body,
form {
display: flex;
flex-flow: column nowrap;
justify-content: center;
align-items: center;
margin: 0 20px;
}
form {
padding: 10px 30px;
}
fieldset {
width: min(50vw, 500px);
}
legend {
font-size: 1.25rem;
}
menu {
margin: 0 20px 10px 0;
}
.list {
list-style-type: lower-latin;
margin: 20px 30px 0 -10px;
}
label {
display: inline-flex;
align-items: flex-start;
transform: translate(12px, -17px);
line-height: 1;
}
button,
input {
font: inherit;
cursor: pointer;
}
.right * {
float: right;
margin-bottom: 20px;
}
<form id="quiz">
<fieldset>
<legend>Quiz</legend>
<menu class="list">
<li><label>
<input name="rad" type="radio" value="A"> Emily should cross through the incorrect information and write in the correct information.
</label></li>
<li><label>
<input name="rad" type="radio" value="B"> Emily does not need to do anything until it is time for her to renew her license.
</label></li>
<li><label>
<input name="rad" type="radio" value="C"> Emily needs to fill out the appropriate paperwork and submit it to the TDLR.
</label></li>
</menu>
<menu class="right">
<button>Done</button>
</menu>
</fieldset>
</form>
<dialog class="A">
<fieldset>
<legend>Message A</legend>
<p>Quote mode. It's called carpe diem Morty. Look it up. Morty! The principal and I have discussed it, a-a-and we're both insecure enough to agree to a three-way! Haha god-damn! </p>
<menu class="right">
<input class="close" type="button" value="OK">
</menu>
</fieldset>
</dialog>
<dialog class="B">
<fieldset>
<legend>Message B</legend>
<p>Yo! What up my glip glops! Lookin' good! Are you kidding? I'm hoping I can get to both of them, Rick! I mixed in some praying mantis DNA. You know a praying mantis is the exact opposite of a vole, Morty? They mate once and then bluergh cut each other's
heads off. </p>
<menu class="right">
<input class="close" type="button" value="OK">
</menu>
</fieldset>
</dialog>
<dialog class="C">
<fieldset>
<legend>Message C</legend>
<p>Get off the high road Summer. We all got pink eye because you wouldn't stop texting on the toilet. Flip the pickle over. Honey, stop raising your father's colesterol so you can take a hot funeral selfie. God? God's turning people into insect monsters
Beth. I'm the one beating them to death. Thank me. </p>
<menu class="right">
<input class="close" type="button" value="OK">
</menu>
</fieldset>
</dialog>

Change a class with a selector using javascript

I'm new to web programming, and I have been trying to do a true/false test, and when the answers are submitted, the answers change colors depending if it's correct or not.
At first, I used labels for each input:
<h3>1. Father Christmas and Santa Claus are the same man</h3>
<input type="radio" id="1bon" name="q1" value="Non" >
<label for="1bon" > True </label> <!-- label is for css -->
<input type="radio" id="1non" name="q1" value="Bon">
<label for="1non" > False </label><br/>
And in the css, I used " input[value=Bon] + label" or "input[value=Non] +label" with a "background color : blue ", and in a JS, I used label[i].style.background to change the color. It's does change the color, but only of the radio button, and when not checked, which is exactly what I'm trying to do. It comes from the fact I don't know how to select the label of a precise input[x=y]:selector.
So I rewrote the whole thing without any labels
<h3>1. Father Christmas and Santa Claus are the same man </h3>
<input type="radio" class="input" id="1bon" name="q1" value="Non"> True
<input type="radio" class="input" id="1non" name="q1" value="Bon"> False
With new css:
.input {
background-color: #fff;
display:inline-block;
width:5%;
padding:10px;
border:1px solid #ddd;
margin-bottom:10px;
cursor:pointer; /* new selectoon type */
}
.input:checked{
background-color: #4876ff;
}
So, when just checked, it is blue, but when the answers are submitted, depending of the value of the input, it change the color of the class:checked.
It there any way do modify the style of a class with a selector in javascript ?
Also, if the user decides to change his answer for a question, the checked have to go back to being color neutral.
Thank you for your help.
You can use this function to change class of element as you explained earlier. But changing color of checkbox is not possible without using third party plugin or customized elements. Please check this link
function Test2($this){
var radios = document.getElementsByName('q1');
for(i=0; i< radios.length; i++){
var element = radios[i];
element.classList.remove("correctAnswer");
element.classList.remove("wrongAnswer");
}
if($this.value === "Non"){//Assume "Non" is correct answer
$this.classList.add("correctAnswer");
}else{
$this.classList.add("wrongAnswer");
}
}

check if all inputs are checked

I have 2 buttons and 2 inputs. The "buy"-button should only fire its default function when both inputs are checked. If not it should mark them with a red border. What am I doing wrong here?
jQuery(function($) {
$('.checkedterms:checked').length == $('.checkedterms').length
$("#upsellyes").click(function(e) {
$(".checkedterms").change(function(){
if (!$('.checkedterms:checked').length == $('.checkedterms').length) {
e.preventDefault();
$("#terms-required").addClass('invalid');
}
else {
$("#terms-required").removeClass('invalid');
}
});
});
});
.invalid {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="terms-required">
<input type="checkbox" class="checkedterms" name="terms" id="terms" style="position: absolute;"><label for="terms" class="checkbox" style="display: inline-block!important;font-weight:normal!important;margin-left: 25px;">I have read <a href="#" >Allgemeinen Geschäftsbedingungen</a>.<span class="required">*</span></label><br />
<input type="checkbox" class="checkedterms" name="terms" id="terms" style="position: absolute;"><label for="terms" class="checkbox" style="display: inline-block!important;font-weight:normal!important;margin-left: 25px;">I have read <a href="#" >Widerrufsbelehrung</a>.<span class="required">*</span></label><br />
</div><br>
buy<br><br>
no thanks
There's a couple of issues here:
You've got an equality check at the start of the code which does nothing.
You've nested the change handler on the checkboxes within the click handler of the button; remove it.
Unrelated to the issue, but you are using duplicate id attributes. They need to be unique within the DOM.
Your logic is backwards. You state that you want the red border to only appear when both checkboxes are not checked when the 'Buy' button is clicked.
You can also make the logic more succinct by caching the checkbox selector and using toggleClass(). Something like this:
jQuery(function($) {
$("#upsellyes").click(function(e) {
var $terms = $('.checkedterms');
$("#terms-required").toggleClass('invalid', $terms.length != $terms.filter(':checked').length);
});
});
.invalid {
border: 1px solid red;
}
.checkedterms {
position: absolute;
}
label {
display: inline-block!important;
font-weight: normal!important;
margin-left: 25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="terms-required">
<input type="checkbox" class="checkedterms" name="terms" />
<label for="terms" class="checkbox">
I have read Allgemeinen Geschäftsbedingungen.
<span class="required">*</span>
</label><br />
<input type="checkbox" class="checkedterms" name="terms" />
<label for="terms" class="checkbox">
I have read <a href="#" >Widerrufsbelehrung</a>.
<span class="required">*</span>
</label><br />
</div><br />
buy<br><br>
no thanks
Finally note the use of a separate stylesheet. Inline styling is a bad idea and should be avoided where possible.
remove this line
$(".checkedterms").change(function(){ //remove
//keep the code that's currently here
}); //remove
leaving you with
jQuery(function($) {
$('.checkedterms:checked').length == $('.checkedterms').length
$("#upsellyes").click(function(e) {
if ($('.checkedterms:checked').length != $('.checkedterms').length) {
e.preventDefault();
$("#terms-required").addClass('invalid');
}
else {
$("#terms-required").removeClass('invalid');
}
});
});
the code wasn't running because you were setting an event listener on the checkboxes inside the event listener on the button. what was happening is that when you clicked the button, javascript would set an event listener on the checkboxes that fires when their state changes
You need an if statement at line 2 and one more '='
if ($('.checkedterms:checked').length === $('.checkedterms').length) {
....
}
and you should put an eventListener each input change

how to change text between input tags and align label checbox and icon on one line

I currently have this:
<script type="text/javascript">
$(document).ready(function(){
/* als je selectbox gebruikt doe dan deze:
$("#deliveryType").change(function(){
$("img[name=deliveryIcon]").attr("src","images/rushdeliveryicon.png");
});
*/
$('#deliveryType').click(function() {
$deliveryType = document.getElementById("deliveryType");
if ($(this).is(':checked') == true) {
$deliveryType.value="spoed";
$('#deliveryType').text("Spoedlevering");
$("img[name=deliveryIcon]").attr("src","images/rushdeliveryicon.png");
}else{
$deliveryType.value="week";
$('#deliveryType').text("Weeklevering");
$("img[name=deliveryIcon]").attr("src","images/weekdeliveryicon.png");
}
});
});
</script>
<label id="deliverylabel" for="delivery">Leveringsoort
<!-- <select name="deliveryType" id="deliveryType" >
<option value="week">Weeklevering</option>
<option value="rush">Spoedlevering</option>
</select>
-->
<input name="deliveryType" id="deliveryType" type="checkbox" value="week" >Weeklevering</input>
<img name="deliveryIcon" src="images/weekdeliveryicon.png" style="width:64px;height:64px;" /></label>
If i click the checkbox then the text between the input tags need to change:
<input name="deliveryType" id="deliveryType" type="checkbox" value="week">Weeklevering</input>
Next to this i also try to get the text of the label and the checkbox + text + icon aligned on 1 line so that it fits like the rest of the input fields on the form. Please have a look:
http://jsfiddle.net/nqm4bpnu/
problem with CSS is that the checkbox input also takes this style:
div.wrapperDiv
{
width:100%;
float:left;
margin-bottom:20px;
}
but it because it is a checkbox it doesnt need to have such a big width.
any ideas
thank you
First thing is <input> doesn't have a closing tag (</input>) so I have changed it to </input>, added a <span> with different id to display the text and changed click to change (this doesn't matter but I prefer change event for check box)
HTML
<label id="deliverylabel" for="delivery">Leveringsoort</label>
<input name="deliveryType" id="deliveryType" type="checkbox" value="week" />
<span id="displayTypeText">Weeklevering</span> <!-- <-----here -->
<img name="deliveryIcon" src="images/weekdeliveryicon.png" style="width:64px;height:64px;" />
JS
$('#deliveryType').change(function () {
if (this.checked) {
this.value = "spoed";
$('#displayTypeText').text("Spoedlevering");
$("img[name=deliveryIcon]").attr("src", "images/rushdeliveryicon.png");
} else {
this.value = "week";
$('#displayTypeText').text("Weeklevering");
$("img[name=deliveryIcon]").attr("src", "images/weekdeliveryicon.png");
}
});
I am not much of a designer but I think you should add a div with float:left around this . Anyways here is a working fiddle,
fiddle
UPDATED
As I have already mentioned I am not a designer but this should get you going (Add it at the end of the CSS script,
#deliveryType{
width:30%!important;
}
updated fiddle
Try using this --
remove 'Weeklevering' from within your input tag
<input name="deliveryType" id="deliveryType" type="checkbox" value="week" >Weeklevering</input>
and make html like this,
<input name="deliveryType" id="deliveryType" type="checkbox" value="week" >
<span id="label">Weeklevering</span>
change blow line in your jquery code -
$('#deliveryType').text("Spoedlevering");
to this,
$('#label').html("Spoedlevering");
Note: Do this to both the instances in your jQuery code.
To make all three items in single line, add following css -
#deliverylabel { display: block; text-align: left; width: 100% !important; }
#deliverylabel > input { display: inline-block; margin-left: 15px; vertical-align: middle; width: auto; }
hope this helps.

Linking checkboxes to text inputs and updating its fields

I am trying to link a checkbox to a text input in order to update the value inside the input field.
My problem is how do I update the value accordingly when the checkbox is ticked. For example, I would like to have a text stating status is "Pending" (with the checkbox unticked) and once the box is ticked, update the value to "Completed" and possibly highlight the text input to a green colour.
Picture:
Code:
<div class="status-updates">
<label class="radio" for="status-updates">
<input type="checkbox" name="status" id="statuses">
</label>
<input type="text" name="pending-completed" id="pending-completed" class="pending-completed" placeholder="Pending">
</div>
Do I need some sort of jQuery to run some sort of input validation?
Would appreciate some help on this.
Thank you.
Try below jquery code(bind .change() event of checkbox) :-
$('#statuses').change(function(){
if($(this).is(':checked'))
{
$("#pending-completed").attr('placeholder','Completed')
}
else
{
$("#pending-completed").attr('placeholder','Pending')
}
});
EDIT(Placeholder with green color) :-
Jquery :
$('#statuses').change(function(){
if($(this).is(':checked'))
{
$("#pending-completed").attr('placeholder','Completed').addClass('green-class')
}
else
{
$("#pending-completed").attr('placeholder','Pending').removeClass('green-class')
}
});
CSS :
.green-class::-webkit-input-placeholder {
color: green;
}
DEMO
Try this : bind change event to checkbox and put placeholder as per checkbox checked status.
$(function(){
$('#statuses').change(function(){
var placeholder = $(this).is(':checked')?"Completed":"Pending";
$("#pending-completed").attr('placeholder',placeholder);
});
});
LIVE DEMO: http://jsfiddle.net/don/qaxow1jz/
jQuery:
$('input[name=status]').change(function() {
var inputText = 'input[name=pending-completed]';
if($(this).is(':checked')) {
$(inputText).attr('placeholder', 'Completed').addClass('highlight');
} else {
$(inputText).attr('placeholder', 'Pending').removeClass('highlight');
}
});
HTML:
<div class="status-updates">
<label class="radio" for="status-updates">
<input type="checkbox" name="status" id="statuses">
</label>
<input type="text" name="pending-completed" id="pending-completed" class="pending-completed" placeholder="Pending">
</div>
CSS:
input.highlight[name=pending-completed]::-webkit-input-placeholder {
color: green;
}
input.highlight[name=pending-completed]:-moz-placeholder {
color: green;
}
input.highlight[name=pending-completed]::-moz-placeholder {
color: green;
}
input.highlight[name=pending-completed]:-ms-input-placeholder {
color: green;
}
Have a look at this . Working example : http://jsfiddle.net/gmwzzL10/
HTML
<div class="status-updates">
<label class="radio" for="status-updates">
<input type="checkbox" name="status" id="statuses" class="checkbox_status">
</label>
<input type="text" name="pending-completed" id="pending-completed" class="pending-completed" placeholder="Pending">
</div>
JS
$("document").ready(function(){
$(".checkbox_status").click(function(){
var inputBox = $(this).closest(".status-updates").find(".pending-completed");
if($(this).is(':checked')){
inputBox.attr("placeholder","Completed").addClass("make-green");
}
else{
inputBox.attr("placeholder","Pending").removeClass("make-green");
}
})
})
CSS
.make-green{
border: 1px solid green;
}

Categories

Resources