Check if multiple radio buttons are checked - javascript

I'm not very good at Javascript, so I would like to ask help with the following:
I have a form, which has multiple radio groups (generated by php code, so I don't know their names OR how many will appear), and I need to check whether they are selected or not.
If not I want to show the user which question was not answered (no alert message, but it can be in text form or the question letters turning red).
I've tried googling the problem, but none of the previous answers were good to use in my case.
Here is my code so far:
function formCheck(formID) {
var eLabel=document.getElementById(formID).getElementsByTagName("label");
var radionames=[];
var eInput=document.getElementById(formID).getElementsByTagName("input");
var checker=true;
for (var i=0; i<eInput.length; i++) {
if (eInput[i].checked) {
radionames.push(eInput[i].name);
}
}
for (var i=0; i<eInput.length; i++) {
for (var j=0; j<radionames.length; j++) {
if (eInput[i]==radionames[j]) {
checker=true;
}
else {
alert();
checker=false;
}
}
}
return checker;
}
<form method="post" action="something.php" id="form1" name="form1">
<div class="que">que 1</div>
<div class="answ"><label><input name="2" value="7" type="radio">Answer 1</label></div>
<div class="answ"><label><input name="2" value="5" type="radio">Answer 2</label></div>
<div class="answ"><label><input name="2" value="8" type="radio">Answer 3</label></div>
<div class="answ"><label><input name="2" value="6" type="radio">Answer 4</label></div>
<div class="que">que 2</div>
<div class="answ"><label><input name="1" value="4" type="radio">Answer 1</label></div>
<div class="answ"><label><input name="1" value="1" type="radio">Answer 2</label></div>
<div class="answ"><label><input name="1" value="2" type="radio">Answer 3</label></div>
<div class="answ"><label><input name="1" value="3" type="radio">Answer 4</label></div>
<input class="submit_button" value="Submit the form" onclick="return formCheck('form1');" type="submit">
</form>
I wanted to create an array with the checked input "group" names, and compare it to all the input group names... the remaining ones will show the error (red text, a message, doesn't matter).
The problem is this code doesn't really do anything that I can see, and shows the something.php even if I don't have anything checked...
If this is not a good method, I'm open to any suggestions.
(I don't want to use jQuery, and the code has to run on older browsers too.)
Sorry for my english, it's not my native language &
Thanks for your help in advance!
A.

in second For loop in javascript :
use this line :
if (eInput[i].value == radionames[j]) {
instead of : if (eInput[i] == radionames[j]) {
you must realy get the value of eInput[i]

You can use document.querySelectorAll to get all input. You can also fine tune it by passing the type of input. Then filter out the name from the group of radio buttons
function getCheckedButton() {
var tempNames = [];
// get all radio button and loop through it to get it's name.
// use a tempArray to keep unique names
var radios = document.querySelectorAll('input').forEach(function(item) {
// if the name is not present then and only then adding name to the array
if (tempNames.indexOf(item.name) === -1) {
tempNames.push(item.name)
}
})
// now looping through temp array
for (var i = 0; i < tempNames.length; i++) {
// using the name to select the radio button group to check if any of radio
// button in this group is checked or not
// if not checked then it will give null
if (document.querySelector('input[name="' + tempNames[i] + '"]:checked') !== null) {
console.log(document.querySelector('input[name="' + tempNames[i] + '"]:checked').value)
} else {
console.log("Radio button of group value " + tempNames[i] + " is unchecked")
}
}
}
<div class="que">
que 1</div>
<div class="answ">
<label>
<input name="2" value="7" type="radio">Answer 1</label>
</div>
<div class="answ">
<label>
<input name="2" value="5" type="radio">Answer 2</label>
</div>
<div class="answ">
<label>
<input name="2" value="8" type="radio">Answer 3</label>
</div>
<div class="answ">
<label>
<input name="2" value="6" type="radio">Answer 4</label>
</div>
<div class="que">que 2</div>
<div class="answ">
<label>
<input name="1" value="4" type="radio">Answer 1</label>
</div>
<div class="answ">
<label>
<input name="1" value="1" type="radio">Answer 2</label>
</div>
<div class="answ">
<label>
<input name="1" value="2" type="radio">Answer 3</label>
</div>
<div class="answ">
<label>
<input name="1" value="3" type="radio">Answer 4</label>
</div>
<button onclick="getCheckedButton()">Get checked buttons</button>

Related

For Loop for select the checked Radio Button

I've tried to take the value of the selected Radio Button through a for loop. Yes it works.
But if no Radio Button is selected I need to show up a message. for that I used a variable called flag. But that part doesn't work.
function selRadio()
{
var i;
var flag="no";
for (i=0;i<=(document.form.ra.length);i++)
{
if (document.form.ra[i].checked)
{
alert(Number(i+1));
flag="yes";
}
}
if (flag=="no")
{
alert("click on some Radio Button");
}
}
<form name="form">
<p>1 <input type="radio" name="ra" id="1"></p>
<p>2 <input type="radio" name="ra" id="2"></p>
<p>3 <input type="radio" name="ra" id="3"></p>
<p>4 <input type="radio" name="ra" id="4"></p>
<p>5 <input type="radio" name="ra" id="5"></p>
<input type="button" value="Click" onClick='seRadio();'>
</form>
Try this,
<script type="text/javascript">
function selRadio()
{
var i;
var flag="no";
for (i=0;i<=(document.form.ra.length);i++)
{
if (typeof document.form.ra[i] != 'undefined' && document.form.ra[i].checked)
{
alert(Number(i+1));
flag="yes";
}
}
if (flag=="no")
{
alert("click on some Radio Button");
}
}
</script>
<form name="form">
<p>1 <input type="radio" name="ra" id="1"></p>
<p>2 <input type="radio" name="ra" id="2"></p>
<p>3 <input type="radio" name="ra" id="3"></p>
<p>4 <input type="radio" name="ra" id="4"></p>
<p>5 <input type="radio" name="ra" id="5"></p>
<input type="button" value="Click" onClick="selRadio();">
</form>
In console, I was getting undefined element index, so checked for undefined condition.
I hope this will solve your problem.
You need to iterate the array elements from 0 to length-1, otherwise you run into an exception and the function selRadio() is terminated before checking flag:
for (i=0;i<(document.form.ra.length);i++)
{
if (document.form.ra[i].checked)
{
alert(Number(i+1));
flag="yes";
}
}
(replace <= with < in the loop condition)

Javascript conditionals not working on correct button combination

I have 5 if else conditions under function getRadioButtonValue. The function does not go through all the conditions even after clicking the right button combinations.
I have tried to debug the script using Chrome Developer tools but the problem still exists. Where is the code breaking?
Some information regarding the page, I am using Javascript to hide the div's and headers so that at any one time there is only one question seen.
Only the first if conditions work, but nothing else
The results are seen after Get Result button is clicked on the last page which should redirect to the appropriate page.
[DELETED CODE]
[UPDATED CODE]
I am unable to auto hide my div's based on the response given below by Keith.
FYI: His code works as expected.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>
.hidden {
display: none;
}
.visible {
display: block;
margin: 0 auto;
width: 650px;
height: 445px;
background: #EFDFBC;
}
</style>
</head>
<body>
<div id="first-question" class="visible">
<h3>How?</h3>
<ul>
<li>abc</li>
<li>def</li>
</ul>
<hr>
<input type="radio" name="quiz-question-one" id="quiz-question-one-yes" value="yes" />
<label for="quiz-question-one-yes" id="oneYes">Yes</label>
<input type="radio" name="quiz-question-one" id="quiz-question-one-no" value="no" />
<label for="quiz-question-one-no" id="oneNo">No</label>
</div>
<div id="second-question" class="hidden">
<h3>To</h3>
<hr>
<input type="radio" name="quiz-question-two" id="quiz-question-two-yes" value="yes" />
<label for="quiz-question-two-yes" id="twoYes">Yes</label>
<input type="radio" name="quiz-question-two" id="quiz-question-two-no" value="no" />
<label for="quiz-question-two-yes" id="twoNo">No</label>
</div>
<div id="third-question" class="hidden">
<h3>Make </h3>
<hr>
<input type="radio" name="quiz-question-three" id="quiz-question-three-yes" value="yes" />
<label for="quiz-question-three-yes" id="threeYes">Yes</label>
<input type="radio" name="quiz-question-three" id="quiz-question-three-no" value="no" />
<label for="quiz-question-three-yes" id="threeNo">No</label>
</div>
<div id="fourth-question" class="hidden">
<h3>This</h3>
<hr>
<input type="radio" name="quiz-question-four" id="quiz-question-four-yes" value="yes" />
<label for="quiz-question-four-yes" id="fourYes">Yes</label>
<input type="radio" name="quiz-question-four" id="quiz-question-four-no" value="no" />
<label for="quiz-question-four-yes" id="fourNo">No</label>
</div>
<div id="fifth-question" class="hidden">
<h3>Work?</h3>
<hr>
<input type="radio" name="quiz-question-five-yes" id="quiz-question-five-yes" value="yes" />
<label for="quiz-question-five-yes" id="fiveYes">Yes</label>
<input type="radio" name="quiz-question-five-no" id="quiz-question-five-no" value="no" />
<label for="quiz-question-five-yes" id="fiveNo">No</label>
</div>
<div class="page result">
<label>Results</label>
<div id="result"></div>
</div>
</body>
</html>
<script type="text/javascript">
var results = {};
function updateResult() {
var r = results,
rt = $('#result');
if (r.quiz-question-one && r.quiz-question-two && r.quiz-question-three && r.quiz-question-four && r.quiz-question-five) {
rt.text('All Yes');
} else if (!r.quiz-question-one && !r.quiz-question-two && !r.quiz-question-three && !r.quiz-question-four && !r.quiz-question-five) {
rt.text('All No');
} else {
rt.text('We have a mixed response');
}
}
$(function () {
$('body').on('click', '[name]', function () {
var $this = $(this),
page = $this.closest('.hidden'),
next_page = $(page.next());
results[$this.attr('name')] = $(this).val() === 'yes';
page.removeClass('visible');
next_page.addClass('visible');
if (next_page.hasClass('result')) updateResult();
});
});
</script>
I've created an example below that I think you can work from. The values from the radio I don't think get updated until you submit, instead I've captured the results in the onclick. You can now add back you CSS styling etc. Hope that helps.
var results = {};
function updateResult() {
var r = results,
rt = $('#result');
if (r.q1 && r.q2 && r.q3) {
rt.text('All Yes');
} else if (!r.q1 && !r.q2 && !r.q3) {
rt.text('All No');
} else {
rt.text('We have a mixed response');
}
}
$(function () {
$('body').on('click', '[name]', function () {
var $this = $(this),
page = $this.closest('.page'),
next_page = $(page.next());
results[$this.attr('name')] = $(this).val() === 'yes';
page.removeClass('active');
next_page.addClass('active');
if (next_page.hasClass('result')) updateResult();
});
});
.page {
display: none;
}
.page.active {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="page active">
<div>Question 1</div>
<label for="q1yes">Yes</label>
<input id="q1yes" type="radio" name="q1" value="yes">
<label for="q1no">No</label>
<input id="q1no" type="radio" name="q1" value="no">
</div>
<div class="page">
<div>Question 2</div>
<label for="q2yes">Yes</label>
<input id="q2yes" type="radio" name="q2" value="yes">
<label for="q2no">No</label>
<input id="q2no" type="radio" name="q2" value="no">
</div>
<div class="page">
<div>Question 3</div>
<label for="q3yes">Yes</label>
<input id="q3yes" type="radio" name="q3" value="yes">
<label for="q3no">No</label>
<input id="q3no" type="radio" name="q3" value="no">
</div>
<div class="page result">
<label>Results</label>
<div id="result"></div>
</div>
<input type="radio" id="quiz-question-one-yes" value="yes" />
<label for="quiz-question-one-yes" id="oneYes">Yes</label>
<input type="radio" id="quiz-question-one-no" value="no" />
<label for="quiz-question-one-no" id="oneNo">No</label>
In the above you are using type="radio", that means all type="radio" with the same name will group together, and not just these two. To group together just give them a name on the input. eg.
<input type="radio" name="quiz-question-one" id="quiz-question-one-yes" value="yes" />
<label for="quiz-question-one-yes" id="oneYes">Yes</label>
<input type="radio" name="quiz-question-one" id="quiz-question-one-no" value="no" />
<label for="quiz-question-one-no" id="oneNo">No</label>
Above you can see I've given the 2 inputs the name="quiz-question-one", and then for the next question maybe give them a name="quiz-question-two" etc..
On another note, there are lots of places where your code could be simplified, but hopefully this will solve your current problem.

Create a report for a form javascript

Hope someone can help.
I have a dynamically generated form that ends up looking like this
<form>
<header><h2 id="title">This is a Survey Title</h2></header>
<ul class="Question_list">
<li class="question">
<div id="sm_survey_question_0">
<fieldset>
<div class="question_text">is this a test?</div>
<input type="radio" name="0" value="1">yes<br>
<input type="radio" name="0" value="2">no<br>
<input type="radio" name="0" value="3">maybe<br>
</fieldset>
</div>
</li>
<li class="question">
<div id="sm_survey_question_1">
<fieldset>
<div class="question_text">Is Batman the best?</div>
<input type="radio" name="1" value="1">yes<br>
<input type="radio" name="1" value="2">no<br>
</fieldset>
</div></li>
<li>
<div id="sm_survey_question_2">
<fieldset>
<div class="question_text">best colors</div>
<input type="radio" name="2" value="1">red<br>
<input type="radio" name="2" value="2">blue<br>
<input type="radio" name="2" value="3">green<br>
</fieldset>
</div>
</li>
</ul>
</form>
and I would like that when the submit button is clicked i can generate a "report", a string would work with the question and the answers selected.
I cant wrap my mind around how to do that.
so far im able to cycle through the questions, check what answers are checked but its the end when i have to create a sting with the questions + its checked
module.createReport = function() {
console.log('reporting');
var questions = document.getElementsByClassName('question');
console.log(questions.length+1,"questions");
var StringAnswers="";
for (var i = questions.length ; i >= 0; i--) {
var textq= document.getElementById('sm_survey_question_'+i).getElementsByClassName("question_text")[0].innerHTML;
var answers = document.getElementById('sm_survey_question_'+i).getElementsByTagName('input');
for (var j = answers.length-1; j >= 0; j--) {
if (answers[j].checked) {
var isanswerC= answers[j].value;
};
var conc= textq+" "+isanswerC;
StringAnswers.concat(conc);
};
};
console.log(conc);
};

Radiobutton on selection do a function

I have two radio buttons. If the user chose one of them i would like my code to execute one particular function. I need to get the value from the radio button selection and push it to my function on the server-side as "valueButton". Guess i need a function on the client-side, but how should that look?
The buttons (client-side):
<div>
<input type="radio" name="origin" id="radio-origin-1" value="ID1">
<label for="radio-origin-auto">Grupp 1</label>
</div>
<div>
<input type="radio" name="origin" id="radio-origin-2" value="ID2">
<label for="radio-origin-en">Grupp 2</label>
</div>
The functions (server-side):
function dataSelect(valueButton){
if (valueButton == "ID1") {
ID1(); }
else if (valueButton == "ID2") {
ID2(); }
}
function ID1(){
MailApp.sendEmail("test.acc#outlook.com", "subjects", GetDataFromSpreadsheet());}
function ID2(){
MailApp.sendEmail("test.acc2#outlook.com", "subjects", GetDataFromSpreadsheet());}
HTML Code
<div>
<input type="radio" name="origin" id="radio-origin-1" value="ID1" onChange="dataSelect(this.value);">
<label for="radio-origin-auto">Grupp 1</label>
</div>
<div>
<input type="radio" name="origin" id="radio-origin-2" value="ID2" onChange="dataSelect(this.value);">
<label for="radio-origin-en">Grupp 2</label>
</div>

How can I make this javascript form validation DRYer?

The user has to select one radio from each of three input "categories". If he "submits" without doing so, he gets a warning:
http://jsfiddle.net/bqyvS/
Markup like this:
<form>
<div id="color">
<input type="radio" name="color" id="blue">
<label for="blue">Blue</label>
<input type="radio" name="color" id="red">
<label for="red">Red</label>
<input type="radio" name="color" id="green">
<label for="green">Green</label>
</div>
<div id="shape">
<input type="radio" name="shape" id="square">
<label for="square">Square</label>
<input type="radio" name="shape" id="circle">
<label for="circle">Circle</label>
<input type="radio" name="shape" id="triangle">
<label for="triangle">Triangle</label>
</div>
<div id="size">
<input type="radio" name="size" id="small">
<label for="small">Small</label>
<input type="radio" name="size" id="medium">
<label for="mediume">Medium</label>
<input type="radio" name="size" id="large">
<label for="large">Large</label>
</div>
</form>
<a id="link" href="#">click me to "submit"</a>
<p id="warning"></p>​
Javascript:
$('#link').on('click', function() {
if (!$('#color input[type=radio]:checked').length) {
$('#warning').html("Oops! Please choose a color!");
}
else if(!$('#shape input[type=radio]:checked').length) {
$('#warning').text("Oops! Please choose a shape!");
}
else if(!$('#size input[type=radio]:checked').length) {
$('#warning').text("Oops! Please choose a size!");
}
});
This is a simplified version of a larger piece of code. How can I rewrite the conditional more efficiently so that I'm not verbosely checking each input name? (There should only be one "warning" displayed per "submit", even if multiple input name categories aren't checked.) Editing the markup would be okay.
Thanks!
When applying behavior to similar groups, you should start thinking about classes instead of ids, in this solution, you don't need a separate data-name but I believe it's better to have data separate from html id, but you could use this.id if you prefer
<form>
<div id="color" class="selection-group" data-name="color">
<input type="radio" name="color" id="blue">
<label for="blue">Blue</label>
<input type="radio" name="color" id="red">
<label for="red">Red</label>
<input type="radio" name="color" id="green">
<label for="green">Green</label>
</div>
<div id="shape" class="selection-group" data-name="square">
<input type="radio" name="shape" id="square">
<label for="square">Square</label>
<input type="radio" name="shape" id="circle">
<label for="circle">Circle</label>
<input type="radio" name="shape" id="triangle">
<label for="triangle">Triangle</label>
</div>
<div id="size" class="selection-group" data-name="size">
<input type="radio" name="size" id="small">
<label for="small">Small</label>
<input type="radio" name="size" id="medium">
<label for="mediume">Medium</label>
<input type="radio" name="size" id="large">
<label for="large">Large</label>
</div>
</form>
<a id="link" href="#">click me to "submit"</a>
<p id="warning"></p>​
Javascript:
$('#link').on('click', function() {
$('.selection-group').each(function() {
if(!$(this).find('input[type=radio]:checked').length) {
$('#warning').html("Oops! Please choose a "+ $(this).data('name') +"!");
return false;
}
});
});
function validationCheck() {
var isValid = true,
errorText = "";
$("form div").each( //get the divs that hold the radios and loop
//$("#color, #shape, #size").each( //could do it by ids of the divs also
function(){
var div = jQuery(this), //div reference
isChecked = div.find('input[type="radio"]:checked').length>0; //see if we have anything selected
if (!isChecked) { //if no selections, show error message
isValid = false; //set validation to false
errorText = "Oops! Please choose a " + div.prop("id") + "!"; //build error message
return false; //exit each loop
}
}
);
$('#warning').text(errorText); //set error message
return isValid;
}
$('#link').on('click', function(){
$('#color, #shape, #size').each(function(i, ele){
if($(this).find('input:checked').length == 0)
$('#warning').text("Oops! Please choose a " + this.id + "!");
});
});
jsFiddle
You may want to consider generating a warning message in the case a user does not select any inputs or only 1 input.
In this example, a user will recieve a message similar to Oops! Please choose a color, and shape!
$('#link').on('click', function(){
var msgs = [];
$('#color, #shape, #size').each(function(i, ele){
if($(this).find('input:checked').length == 0)
msgs.push(this.id);
});
if(msgs.length > 0)
$('#warning').text("Oops! Please choose a " + msgs.join(", and "));
});
jsFiddle

Categories