How to check radio button is checked on form submit - JavaScript - javascript

I have a form using radio buttons for the user to select a rating between 1-10. Some of these questions are required to have a rating before the user is able to submit. So i call for the function validateForm() on submit to do so.
Example of radio buttons:
<div class="fluid_container">
<label for="ease-rating-0">
<input type="radio" name="ease-rating" class="hover-select-ease" id="ease-rating-0" value="0" />
<div class="box-number-half number-padding">0</div>
</label>
<label for="ease-rating-1">
<input type="radio" name="ease-rating" class="hover-select-ease" id="ease-rating-1" value="1" />
<div class="box-number-half number-padding">1</div>
</label>
<label for="ease-rating-2">
<input type="radio" name="ease-rating" class="hover-select-ease" id="ease-rating-2" value="2" />
<div class="box-number-half number-padding">2</div>
</label>
<label for="ease-rating-3">
<input type="radio" name="ease-rating" class="hover-select-ease" id="ease-rating-3" value="3" />
<div class="box-number-half number-padding">3</div>
</label>
<label for="ease-rating-4">
<input type="radio" name="ease-rating" class="hover-select-ease" id="ease-rating-4" value="4" />
<div class="box-number-half number-padding">4</div>
</label>
<label for="ease-rating-5">
<input type="radio" name="ease-rating" class="hover-select-ease" id="ease-rating-5" value="5" />
<div class="box-number-half number-padding">5</div>
</label>
<label for="ease-rating-6">
<input type="radio" name="ease-rating" class="hover-select-ease" id="ease-rating-6" value="6" />
<div class="box-number-half number-padding">6</div>
</label>
<label for="ease-rating-7">
<input type="radio" name="ease-rating" class="hover-select-ease" id="ease-rating-7" value="7" />
<div class="box-number-half number-padding">7</div>
</label>
<label for="ease-rating-8">
<input type="radio" name="ease-rating" class="hover-select-ease" id="ease-rating-8" value="8" />
<div class="box-number-half number-padding">8</div>
</label>
<label for="ease-rating-9">
<input type="radio" name="ease-rating" class="hover-select-ease" id="ease-rating-9" value="9" />
<div class="box-number-half number-padding">9</div>
</label>
<label for="ease-rating-10">
<input type="radio" name="ease-rating" class="hover-select-ease" id="ease-rating-10" value="10" />
<div class="box-number-half">10</div>
</label>
</div>
An example of my form:
Visual Example
I have success with the following code for "ease of placing order" question:
function validateForm() {
var easeradios = document.getElementsByName("ease-rating");
for (var i = 0; i < easeradios.length; i++) {
if (easeradios[i].checked) {
return true;
}
} return false;
}
I am grabbing the radio buttons by their name which for this is ease-rating. This works fine and the user cannot submit until a rating is selected on this question. However when i try to apply the same to the next row as this is also required it seems to go wrong.
function validateForm() {
var easeradios = document.getElementsByName("ease-rating");
for (var i = 0; i < easeradios.length; i++) {
if (easeradios[i].checked) {
return true;
}
} return false;
var convradios = document.getElementsByName("conv-rating");
for (var i = 0; i < convradios.length; i++) {
if (convradios[i].checked) {
return true;
}
} return false;
}
It seems to only acknowledge a requirement for "Convenience of delivery" before submitting instead of taking the first questions requirement now.
Sorry i'm new to this but what i want is for the form to check that a rating is selected on each question before proceeding. I don't want to use /required as i want to insert custom error message underneath the rating required which is why i haven't used that.
Thanks for your help!

Your are returning from the for loops too early, which is why the rest of the code where conradios for loop resides is unreachable.
Correct this by place the return false; statement just before the last curly brace of the for loop, not after it.
for (var i = 0; i < easeradios.length; i++) {
if (easeradios[i].checked) {
return true;
}
return false;
}
Do the same for the second loop as well:
for (var i = 0; i < convradios.length; i++) {
if (convradios[i].checked) {
return true;
}
return false;
}

Related

How to toggle HTML radio button with jQuery?

I have a radio button that is checked by default. What I am trying to accomplish is just to toggle it on/off with a click and simple logic but I do not understand what I'm doing wrong.
Here is my HTML:
<input type="radio" id="member" name="member" value="member" checked>
<label for="member" >Member Reported</label>
And here is my jQuery:
$('#member').click((e) => {
console.log('click')
if($('#member').is(':checked')) {
$('#member').prop('checked',false)
}
})
This works great, but I noticed that it's not changing the DOM once clicked, and furthermore, when I try to add the prop to true (like below), it's not checking back on the GUI.
Here's the DOM:
$('#member').click((e) => {
console.log('click')
if($('#member').is(':checked')) {
$('#member').prop('checked',false)
} else if (!$('#member').is(':checked')) {
$('#member').prop('checked',true)
}
})
How about this? Is this what you are willing?
$('#member + label').click((e) => {
console.log($('#member')[0].checked);
if($('#member')[0].checked) {
$('#member')[0].checked = false;
} else{
$('#member')[0].checked = true;
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" id="member" name="member" value="member" checked >
<label for="" >Member Reported</label>
As long checked exist in element, it will stay checked. You will have to remove it via jquery to make it work.
You can check functioning here.
<input type="radio" checked>
<br>
<input type="radio" checked="true">
<br>
<input type="radio" checked="false">
<br>
<input type="radio">
I think that's the way it should be.
$('.radios').click((e) => {
$('.radios').each(function (i) {
$(this).removeAttr('checked')
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" id="member" class="radios" name="member" value="member" >
<label for="member" >Member Reported</label><br/>
<input type="radio" id="member2" class="radios" name="member" value="member" >
<label for="member2" >Member Reported2</label><br/>
<input type="radio" id="member3" class="radios" name="member" value="member" checked>
<label for="member3" >Member Reported3</label><br/>

How to check if dynamically generated radio button are clicked in the form?

I am generating a form with multiple choice questions using php , Now I want to check if each and every question has been answered or not by checking if radio buttons for each question are clicked.
<div class="opt">
<div class="row1">
<label class="label">{{ $question->question }}</label>
</div>
<div class="ans">
$answer=$answers[$question->id]
#foreach ($answer as $answer)
<label class="btn btn-default no-margin-rule" >
<input type="radio" name="{{$count+1}}" value="{{$answer->id}}" id="ans{{$answer->answer}}" />
<span class="option{{$answer->answer+1}}"></span>
</label>
#endforeach
</div>
</div>
$("#sub").click(function() {
var check = true;
$("input:radio").each(function() {
var name = $(this).attr('name');
if ($("input:radio[name=" + name + "]:checked").length) {
check = true;
} else {
check = false;
}
});
if (check) {
$("#form1").submit();
} else {
swal("Oops!", "Please select at least one answer in each question.", "error")
}
});
Assuming that there are multiple questions, as you state in the comments under the question, then all you need to check the total number of .ans elements matches the number of .ans elements which contain a checked radio, like this:
$("#sub").click(function() {
var $answers = $('.ans');
var valid = $answers.length == $answers.filter(':has(:radio:checked)').length;
if (valid ) {
$("#form1").submit();
} else {
swal("Oops!", "Please select at least one answer in each question.", "error")
}
});
As a side note I would suggest you do perform this check under the submit event of the form element, instead of the click of a button, for accessibility reasons.
This is - as always - very easy to achieve using standard vanilla Javascript. No jQuery necessary.
document.forms[0].addEventListener('submit', (event) => {
const check = [...document.forms[0].querySelectorAll('fieldset')].every(fieldset => !!fieldset.querySelector('input:checked'));
console.log(`${check ? 'A' : 'Not a'}ll questions have been answered!`);
// for demo purposes, prevent the submit regardless
event.preventDefault();
// in your code, you'd do the check
// if (!check) event.preventDefault();
})
form { display: flex; }
<form id="questions">
<fieldset>
<legend>What is 1+1?</legend>
<input type="radio" name="addition" id="addition1" value="3" />
<label for="addition1">3</label>
<br />
<input type="radio" name="addition" id="addition2" value="1" />
<label for="addition2">1</label>
<br />
<input type="radio" name="addition" id="addition3" value="2" />
<label for="addition3">2</label>
<br />
</fieldset>
<fieldset>
<legend>What is 1*1?</legend>
<input type="radio" name="multiplication" id="multiplication1" value="3" />
<label for="multiplication1">3</label>
<br />
<input type="radio" name="multiplication" id="multiplication2" value="1" />
<label for="multiplication2">1</label>
<br />
<input type="radio" name="multiplication" id="multiplication3" value="2" />
<label for="multiplication3">2</label>
<br />
</fieldset>
<fieldset>
<legend>What is 1-1?</legend>
<input type="radio" name="subtraction" id="subtraction1" value="-1" />
<label for="subtraction1">-1</label>
<br />
<input type="radio" name="subtraction" id="subtraction2" value="0" />
<label for="subtraction2">0</label>
<br />
<input type="radio" name="subtraction" id="subtraction3" value="1" />
<label for="subtraction3">1</label>
<br />
</fieldset>
<button type="submit">Submit</button>
</form>

show and hide method: is there something wrong with code? missing? can i show/hide the elements between radioboxes?

Area of the code that will be show/hide, I want to display the objects inside the radiobox (another sets of radioboxes)
<input type="checkbox" name="area" id="chk" onclick="showHide(this.checked);"/>
<label for="chk">Billing & Credit Management Systems</label><br />
<label class="hidden"> Web Billing </label> <input type="radio" name="area1" class="hidden"/>
<label class="hidden"> Web Billing </label> <input type="radio" name="area1" class="hidden"/>
You're calling hiddeninputs(i) like a function. You should use hiddeninputs[i] instead so that you access the value at the index.
You also don't need to get the checkbox element again since you're passing the checked value as a parameter to the function.
Fixed code:
function showHide(checked) {
var hiddeninputs = document.getElementsByClassName("hidden");
for (var i = 0; i != hiddeninputs.length; i++) {
if (checked) {
hiddeninputs[i].style.display = "block";
} else {
hiddeninputs[i].style.display = "none";
}
}
}
.hidden {
display: none;
}
<input type="checkbox" name="area" id="chk" onclick="showHide(this.checked);" />
<label for="chk">Billing & Credit Management Systems</label><br />
<label class="hidden"> Web Billing </label> <input type="radio" name="area1" class="hidden" />
<label class="hidden"> Web Billing </label> <input type="radio" name="area1" class="hidden" />
You need to access elements using [index] and not (index).
[] is used to access an array by index where () is used to call a method.
Also it will be easier to put the elements you want to hide inside of a single parent container.
function showHide() {
var chckbox = document.getElementById("chk");
var hidden = document.getElementsByClassName("hidden");
for (var i = 0; i != hidden.length; i++) {
if (chckbox.checked) {
hidden[i].style.display = "block";
} else {
hidden[i].style.display = "none";
}
}
}
.hidden {
display: none;
}
<input type="checkbox" name="area" id="chk" onclick="showHide(this.checked);" />
<label for="chk">Billing & Credit Management Systems</label><br />
<div class="hidden">
<label> Web Billing </label> <input type="radio" name="area1" />
<label> Web Billing </label> <input type="radio" name="area1" />
</div>
You can do this by using pure css, however, it requires to place checkbox and element beside.
p {
display: none;
}
input:checked + p {
display: block;
}
<input type="radio" name="gender" value="male">
Male
<p>I'm Male</p>
<input type="radio" name="gender" value="female"> Female
<p>I'm Female</p>

using javascript to get radio button values of multiple forms

Note: I am just learning javascript. So please no jQuery answers yet. I'll get there.
I have 7 forms, all with groups of radio buttons, that appear one-by-one as one button of each form is clicked. Works fine. But by the time I'm done, I may have dozens of forms. There has to be a better way to get the value of a clicked button that creating a getValue for each form. Here's what I've done that works:
<script>
function initdisplay() {
document.getElementById("painLocation").style.display="block";
document.getElementById("painSystem").style.display="none";
document.getElementById("painTemporPatt").style.display="none";
document.getElementById("painIntensDur").style.display="none";
document.getElementById("painEtiology").style.display="none";
document.getElementById("painKav").style.display="none";
}
window.onload = initdisplay;
var painLocationValue = 0;
var painSystemValue = 0;
var painTemporPattValue = 0;
var painIntesDurValue = 0;
var painEtiologyValue = 0;
var painKavValue = 0;
function getPainLocationValue() {
var radioButtons = document.getElementsByName("location");
for (var i = 0; i < radioButtons.length; i++) {
if (radioButtons[i].checked) {
painLocationValue = radioButtons[i].value;
document.getElementById("painLocation").style.display="none";
document.getElementById("painSystem").style.display="block";
alert(painLocationValue);
}
}
}
// ... other similar methods here
function getPainKavValue() {
var radioButtons = document.getElementsByName("kav");
for (var i = 0; i < radioButtons.length; i++) {
if (radioButtons[i].checked) {
painKavValue = radioButtons[i].value;
document.getElementById("painKav").style.display="none";
alert(radioButtons[i].value);
}
}
}
</script>
</head>
Then the HTML looks like this:
<body>
<form id="painLocation" action="">
<p class="formPainCode">Q1: What is the location of your ailment?</p>
<input type="radio" name="location" value="000" onclick="getPainLocationValue()"> Head, Face, Mouth<br><br>
<input type="radio" name="location" value="100" onclick="getPainLocationValue()"> Cervical (neck) Region<br><br>
<input type="radio" name="location" value="200" onclick="getPainLocationValue()"> Upper Shoulder and Upper Limbs<br><br>
<input type="radio" name="location" value="300" onclick="getPainLocationValue()"> Thoracic (chest) Region<br><br>
<input type="radio" name="location" value="400" onclick="getPainLocationValue()"> Abdominal Region<br><br>
<input type="radio" name="location" value="500" onclick="getPainLocationValue()"> Lower Back, Lumbar Spine, Sacrum, Coccyx<br><br>
<input type="radio" name="location" value="600" onclick="getPainLocationValue()"> Lower Limbs<br><br>
<input type="radio" name="location" value="700" onclick="getPainLocationValue()"> Pelvic Region<br><br>
<input type="radio" name="location" value="800" onclick="getPainLocationValue()"> Anal, Perineal, Genital Region<br><br>
<input type="radio" name="location" value="900" onclick="getPainLocationValue()"> More than one location<br><br>
</form>
...
<form id="painKav" action="">
<p class="formPainCode">Q11: On which side of your body is your ailment?</p>
<input type="radio" name="kav" value="R" onclick="getPainKavValue()"> Right<br><br>
<input type="radio" name="kav" value="L" onclick="getPainKavValue()"> Left<br><br>
<input type="radio" name="kav" value="C" onclick="getPainKavValue()"> Center<br><br>
<input type="radio" name="kav" value="M" onclick="getPainKavValue()"> More than one side<br><br>
</form>
</body>
</html>
After another couple of frustrating hours, I dropped my "no jQuery" condition. The rest was simple. I used the following code to detect a click, and get the value of the button clicked. And since I expected some of my forms to include input types other than radio buttons, I changed that as well. At this point, the jQuery looks like this:
<script>
$(document).ready(function () {
$("input").click(function() {
var painCode = $(this).val();
alert("The painCode for this person is " + painCode);
});//end click function
}); //end document ready
</script>
I cleaned up the html. A typical form now looks like this:
<div id="painIntensDur">
<form class="painCodeForm" action="">
<p class="formPainCode">Q4: If you experience pain from your ailment, which of the following best describes its intensity and duration? </p>
<input type="radio" name="intensdur" value=".1" > Mild and less than 1 month<br><br>
<input type="radio" name="intensdur" value=".8" > Mild and 1 to 6 months<br><br>
<input type="radio" name="intensdur" value=".9" > Mild and more than 6 months<br><br>
<input type="radio" name="intensdur" value=".4" > Medium and less than 1 month<br><br>
<input type="radio" name="intensdur" value=".2" > Medium and 1 to 6 months<br><br>
<input type="radio" name="intensdur" value=".3" > Medium and more than 6 months<br><br>
<input type="radio" name="intensdur" value=".7" > Severe and less than 1 month<br><br>
<input type="radio" name="intensdur" value=".5" > Severe and 1 to 6 months<br><br>
<input type="radio" name="intensdur" value=".6" > Severe and more than 6 months<br><br>
<input type="radio" name="intensdur" value=".0" > Not sure<br><br>
</form>
</div>
Thanks again to the excellent advice. I'm sure it will come in handy later.

Pass all checkboxes values as an array in Javascript

I have the below checkboxes and I need to get them as an array values.
<input type="checkbox" id="contact_id" value="4" />
<input type="checkbox" id="contact_id" value="3" />
<input type="checkbox" id="contact_id" value="1" />
<input type="checkbox" id="contact_id" value="5" />
I need to pass them to one ajax request as array as below:
xmlHttp.open("POST","?action=contact&contact_id=" +contacts,true);
I am using this function to get the values but not able to pass them to the function as array, the passed like this 4,3,1,5. I need them to be passed like this
contact_id[]=4&contact_id[]=3&contact_id[]=1&contact_id[]=5
I have done this as follows
function getContacts(){
var contacts = document.myform.contact_id, ids = [];
for (var i = 0; i < contacts.length; i += 1){
if (contacts[i].checked)
ids.push(contacts[i].value);
}
return ids;
}
http://jsfiddle.net/xQezt/
Does this fiddle do what you want? The serialization is naive, but you could find a proper way to do that exact thing elsewhere or by using a framework like Zepto, jQuery or YUI.
First I made a way to "submit" the data. The output goes to the console, so open your firebug. Could go anywhere, though.
//submit event registration
submitButton.onclick = function () {
var contactArray = inputsToArray(contacts.children);
var data = serializeArray(contactArray, 'contact_id[]');
console.log(data);
}
Then I made your method "getContacts" more generic:
function inputsToArray (inputs) {
var arr = [];
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked)
arr.push(inputs[i].value);
}
return arr;
}
Here is the naive serialization function. I do not expect this to work well in all cases, so you should do some research in where to get a good serialization algo from:
function serializeArray (array, name) {
var serialized = '';
for(var i = 0, j = array.length; i < j; i++) {
if(i>0) serialized += '&';
serialized += name + '=' + array[i];
}
return serialized;
}
I also slightly modified your HTML:
<div id="contacts">
<input type="checkbox" value="4" />
<input type="checkbox" value="3" />
<input type="checkbox" value="1" />
<input type="checkbox" value="5" />
</div>
<button id="submit">Submit</button>
Which let me query the DOM like this:
var d=document;
var submitButton = d.getElementById('submit');
var contacts = d.getElementById('contacts');
Your input's id are duplicate. so I recommend you to use name instead of id
For Example, Your HTML will look like this :
<form id='contactform'>
<input type="checkbox" name="contact[]" value="4" />
<input type="checkbox" name="contact[]" value="3" />
<input type="checkbox" name="contact[]" value="1" />
<input type="checkbox" name="contact[]" value="5" />
</form>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
Then if you want to get the value to querystring then use the JQuery Serialize
$('#contactform').serialize();
// this will take some thing like this, Example check the second and the fourth
// contact%5B%5D=3&contact%5B%5D=5
jsFiddle : http://jsfiddle.net/Eqb7f/
$(document).ready(function() {
$("#submit").click(function(){
var favorite = [];
$.each($("input[class='check']:checked"), function(){
favorite.push($(this).val());
});
document.getElementById('fav').value = favorite.join(", ");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="cd-form-list">
<div>
<input type="checkbox" id="cd-checkbox-2" class="check" value="A">
<label for="cd-checkbox-1">A for Apple</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-2" class="check" value="B">
<label for="cd-checkbox-2">B for Ball</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-3" class="check" value="C">
<label for="cd-checkbox-3">C for Cat</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-4" class="check" value="D">
<label for="cd-checkbox-4">D for Dog</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-5" class="check" value="E">
<label for="cd-checkbox-5">E for Ear</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-6" class="check" value="F">
<label for="cd-checkbox-6">F for Fish</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-7" class="check" value="G">
<label for="cd-checkbox-7">G for God</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-8" class="check" value="H">
<label for="cd-checkbox-8">H for Hen</label>
</div>
</div>
<div>
<input type="submit" value="Submit" id="submit">
</div>
<input name="services" id="fav">

Categories

Resources