For Loop for select the checked Radio Button - javascript

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)

Related

Event listeners for both radio buttons and text input

I have a group of radio buttons and a text input field:
<div>
<input type="radio" value="0.1" id="radioOne" name="discount" />
<label for="radioOne" class="radio">10%</label>
</div>
<div>
<input type="radio" value="0.2" id="radioTwo" name="discount" />
<label for="radioTwo" class="radio">20%</label>
</div>
<div>
<input type="radio" value="0.3" id="radioThree" name="discount" checked />
<label for="radioThree" class="radio">30%</label>
</div>
<input type="number" name="price" id="priceInput" placeholder="Price">
<p id="resultToast"> </p>
And I wanna the result of final price calculated by Price * Discount and updating the <p id="resultToast"> </p>.
So I did
const radios = document.querySelector('input[name="discount"]:checked');
const toast = document.querySelector('#resultToast');
const priceIn = document.querySelector("#priceInput");
if (radios) {
document.querySelectorAll('input[name="discount"]').forEach((elem) => {
elem.addEventListener("change", function(event) {
radios.value = event.target.value;
console.log(radios.value);
if(priceIn){
toast.textContent = 'final price: ' + radios.value * priceIn.value;
}
});
});
}
if(priceIn){
priceIn.addEventListener('input', updateValue);
}
function updateValue(e) {
toast.textContent = 'final price: ' + e.target.value * radios.value;
}
From the console, the radios.value not updated correctly after clicking the radio buttons. What I did wrong?
Just change:
const radios = document.querySelector('input[name="discount"]:checked');
To:
const radios = document.querySelectorAll('input[name="discount"]:checked');
See working snippet:
const radios = document.querySelectorAll('input[name="discount"]:checked');
const toast = document.querySelector('#resultToast');
const priceIn = document.querySelector("#priceInput");
if (radios) {
document.querySelectorAll('input[name="discount"]').forEach((elem) => {
elem.addEventListener("change", function(event) {
radios.value = event.target.value;
console.log(radios.value);
if(priceIn){
toast.textContent = 'final price: ' + radios.value * priceIn.value;
}
});
});
}
if(priceIn){
priceIn.addEventListener('input', updateValue);
}
function updateValue(e) {
toast.textContent = 'final price: ' + e.target.value * radios.value;
}
<div>
<input type="radio" value="0.1" id="radioOne" name="discount" />
<label for="radioOne" class="radio">10%</label>
</div>
<div>
<input type="radio" value="0.2" id="radioTwo" name="discount" />
<label for="radioTwo" class="radio">20%</label>
</div>
<div>
<input type="radio" value="0.3" id="radioThree" name="discount" checked />
<label for="radioThree" class="radio">30%</label>
</div>
<input type="number" name="price" id="priceInput" placeholder="Price">
<p id="resultToast"> </p>
Reason for this is because you stored the initial
document.querySelector('input[name="discount"]:checked');
value as radios. Now that we look for all, it changes accordingly.
You are referring to a constant you defined at the beginning of your script. This will always give you the same radio button value (the one being checked at the beginning). Do something like
let discount=document.querySelector("input[name=discount]:checked").value
within your event handler function to get the current value of the radio button group.
You could also declutter(=shorten) your code a bit and make it reusable for multiple input sections that way, see below:
function qs(sel,el){return (el||document).querySelector(sel);}
function makeInteractive(frmsel){
const frm=qs(frmsel),
prc=qs("[name=price]",frm),
res=qs(".result",frm);
frm.onchange=calc;
frm.oninput= calc;
function calc(){
res.textContent=
(prc.value * qs("[type=radio]:checked",frm).value)
.toFixed(2);
}
}
makeInteractive("#frm1");
makeInteractive("#frm2");
<form id="frm1">
the first item ...
<div>
<label><input type="radio" value="0.1" name="discount"/>10%</label>
</div>
<div>
<label><input type="radio" value="0.2" name="discount"/>20%</label>
</div>
<div>
<label><input type="radio" value="0.3" name="discount" checked/>30%</label>
</div>
<input type="number" name="price" id="priceInput" placeholder="Price">
<p id="resultToast" class="result"> </p>
</form>
<form id="frm2">
the second item ...
<div>
<label><input type="radio" value="0.1" name="discount"/>10%</label>
</div>
<div>
<label><input type="radio" value="0.2" name="discount"/>20%</label>
</div>
<div>
<label><input type="radio" value="0.3" name="discount" checked/>30%</label>
</div>
<input type="number" name="price" id="priceInput" placeholder="Price">
<p id="resultToast" class="result"> </p>
</form>

Check if multiple radio buttons are checked

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>

JavaScript Quiz – animation has glitch when changing classes with jQuery (Animation Que Buildup)

function main() {
$('.btnBack').click(function () {
var currentSlide = $('.active-slide').stop().fadeOut(500).removeClass('active-slide');
currentSlide.prev().stop().fadeIn(500).addClass('active-slide');
});
$('.btnNext1').click(function() {
var checkedRadioButtons = $(':radio:checked[name=q1]');
if(!checkedRadioButtons.length) {
alert('please select an answer before you proceed!');
}
else {
var currentSlide = $('.active-slide').stop().fadeOut(500).removeClass('active-slide');
currentSlide.next().stop().fadeIn(500).addClass('active-slide'); }
});
$('.btnNext2').click(function() {
var checkedRadioButtons = $(':radio:checked[name=q2]');
if(!checkedRadioButtons.length) {
alert('please select an answer before you proceed!');
}
else {
var currentSlide = $('.active-slide').stop().fadeOut(500).removeClass('active-slide');
currentSlide.next().stop().fadeIn(500).addClass('active-slide'); }
});
$('.btnNext3').click(function() {
var checkedRadioButtons = $(':radio:checked[name=q3]');
if(!checkedRadioButtons.length) {
alert('please select an answer before you proceed!');
}
else {
var currentSlide = $('.active-slide').stop().fadeOut(500).removeClass('active-slide');
currentSlide.next().stop().fadeIn(500).addClass('active-slide');
}
});
}
$(document).ready(main);
function btnSubmit_onclick() {
var myForm = document.form1;
var totalScore = 0;
var value;
var q1Ans = document.getElementById('q1correct');
if(q1Ans.checked == true) {
totalScore ++;
}
var q2Ans = document.getElementById('q2correct');
if(q2Ans.checked == true) {
totalScore ++;
}
var q3Ans = document.getElementById('q3correct');
if(q3Ans.checked == true) {
totalScore ++;
}
myForm.showResults.value ="your total score is "
+ totalScore + "/3!";
}
.slide {
display: none;
}
.slide.active-slide {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<form name="form1" action="" method="post">
<div class="slide active-slide">
<h3>Question 1: Answer is A!</h3>
<input type="radio" name="q1" id="q1correct" >A</input><br>
<input type="radio" name="q1" >B</input><br>
<input type="radio" name="q1" >C</input><br>
<input type="radio" name="q1" >D</input>
<input type="button" class="btnBack" value="Back">
<input type="button" class="btnNext1" value="Next" >
</div>
<div class="slide">
<h3>Question 2: Answer is B! </h3>
<input type="radio" name="q2" >A</input><br>
<input type="radio" name="q2" id="q2correct">B</input><br>
<input type="radio" name="q2" >C</input><br>
<input type="radio" name="q2" >D</input>
<input type="button" class="btnBack" value="Back">
<input type="button" class="btnNext2" value="Next">
</div>
<div class="slide">
<h3>Question 3: Answer is B! </h3>
<input type="radio" name="q3">A</input><br>
<input type="radio" name="q3" id="q3correct">B</input><br>
<input type="radio" name="q3">C</input><br>
<input type="radio" name="q3">D</input>
<input type="button" class="btnBack" value="Back">
<input type="button" class="btnNext3" value="Submit"
onclick="btnSubmit_onclick()">
</div>
<div class="slide">
<h3>Your Total Score</h3>
<textarea name="showResults" rows="8" cols="40" readonly="readonly"></textarea>
<input type="button" class="btnBack" value="Back">
</div>
</form>
</body>
I'm creating a quiz with JavaScript where I'm trying to have 1 question appear at a time.
I’ve successfully hid and shown questions through changing classes with jQuery and CSS. However, the animations glitch when showing the next slide. The next slide is shown under the previous slide and it takes time for the previous slide to disappear.
Doing some research I've seen I've tried using the stop() method about animation que buildup, but that too doesn't seem to fix the problem.
My jQuery is the following
$('.btnBack').click(function () {
var currentSlide = $('.active-slide').stop().fadeOut(500).removeClass('active-slide');
currentSlide.prev().stop().fadeIn(500).addClass('active-slide');
});
$('.btnNext1').click(function() {
var currentSlide = $('.active-slide').stop().fadeOut(500).removeClass('active-slide');
currentSlide.next().stop().fadeIn(500).addClass('active-slide'); }
});
CSS
.slide {
display: none;
}
.slide.active-slide {
display: block;
}
HTML
<div class="slide active-slide">
<h3>Question 1: Answer is A!</h3>
<input type="radio" name="q1" id="q1correct" >A</input><br>
<input type="radio" name="q1" >B</input><br>
<input type="radio" name="q1" >C</input><br>
<input type="radio" name="q1" >D</input>
<input type="button" class="btnBack" value="Back">
<input type="button" class="btnNext1" value="Next" >
</div>
<div class="slide">
<h3>Question 2: Answer is B! </h3>
<input type="radio" name="q2" >A</input><br>
<input type="radio" name="q2" id="q2correct">B</input><br>
<input type="radio" name="q2" >C</input><br>
<input type="radio" name="q2" >D</input>
<input type="button" class="btnBack" value="Back">
<input type="button" class="btnNext2" value="Next">
</div>
The jQuery seems right and no error message appears on the console.
Your help is greatly appreciated.
If you want the animation to fade out the previous question, then fade in the next, you need to wait for the fade to complete before continuing by using the fadeOut callback:
$('.btnBack').click(function() {
var currentSlide = $('.active-slide').stop().fadeOut(500, function() {
$(this).removeClass('active-slide');
currentSlide.prev().stop().fadeIn(500).addClass('active-slide');
});
});
$('.btnNext1').click(function() {
var currentSlide = $('.active-slide').stop().fadeOut(500, function() {
$(this).removeClass('active-slide');
currentSlide.next().stop().fadeIn(500).addClass('active-slide');
});
});
Note that I've moved the code that follows the fadeOut into the fadeOut callback.
Also note that the above relies on the fact you have only a single question matching .active-slide, because fadeOut will call its callback when each animated element finishes. In our case, that's just one so it's fine, but it's worth pointing out.
Live Example:
$('.btnBack').click(function() {
var currentSlide = $('.active-slide').stop().fadeOut(500, function() {
$(this).removeClass('active-slide');
currentSlide.prev().stop().fadeIn(500).addClass('active-slide');
});
});
$('.btnNext1').click(function() {
var currentSlide = $('.active-slide').stop().fadeOut(500, function() {
$(this).removeClass('active-slide');
currentSlide.next().stop().fadeIn(500).addClass('active-slide');
});
});
.slide {
display: none;
}
.slide.active-slide {
display: block;
}
<div class="slide active-slide">
<h3>Question 1: Answer is A!</h3>
<input type="radio" name="q1" id="q1correct">A
<br>
<input type="radio" name="q1">B
<br>
<input type="radio" name="q1">C
<br>
<input type="radio" name="q1">D
<input type="button" class="btnBack" value="Back">
<input type="button" class="btnNext1" value="Next">
</div>
<div class="slide">
<h3>Question 2: Answer is B! </h3>
<input type="radio" name="q2">A
<br>
<input type="radio" name="q2" id="q2correct">B
<br>
<input type="radio" name="q2">C
<br>
<input type="radio" name="q2">D
<input type="button" class="btnBack" value="Back">
<input type="button" class="btnNext2" value="Next">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Totalling the value of two radio buttons as a shopping cart

The issue is:
I have four radio buttons and a check box.
Two radio buttons are with one name and two with another.
The last radio buttons with same name appear only when the check box is checked.
What I want is add the value of first radio button and the value of radio button that appears after the checkbox is checked.
So how do I total the two values using javascript or any other technique. I need it asap as I am working on a project. I need that to be done as in a shopping cart. It means if the user selects another radio button then the value of earlier one should be subtracted and the value of new one added.
<script>
// get list of radio buttons with name 'size'
var sz = document.forms['de'].elements['type'];
// loop through list
for (var i=0, len=sz.length; i<len; i++) {
sz[i].onclick = function() { // assign onclick handler function to each
// put clicked radio button's value in total field
var m=this.form.elements.total.value = this.value;
};
}
var sa = document.forms['de'].elements['glass'];
// loop through list
for (var i=0, len=sa.length; i<len; i++) {
sa[i].onclick = function() { // assign onclick handler function to each
// put clicked radio button's value in total field
var n=this.form.elements.total1.value = this.value;
};
}
$(document).ready(function () {
$('.a').hide();
$('#checkb').click(function () {
var $this = $(this);
if ($this.is(':checked')) {
$('.a').show();
} else {
$('.a').hide();
}
});
});
</script>
<form action="sum.php" method="post" name="de">
<fieldset>
<table align="center">
<tr><td align="center" colspan="100sp"><label><input type="radio" name="type" value="200" />Ordinary (Rs. 200)</label>
<tr><td align="center" colspan="100sp"><label><input type="radio" name="type" value="500" />Original (Rs. 500)</label>
<tr><td colspan="100sp"><label>Do You want a screen guard or a tempered glass?</label><input type="checkbox" name="screen" value="yes" id="checkb" />
<tr><td align="center" colspan="100sp"><label class="a"><input type="radio" class="a" name="glass" value="100" />Screen Guard (Rs. 100)</label>
<tr><td align="center" colspan="100sp"><label class="a"><input type="radio" class="a" name="glass" value="200" />Tempered Glass (Rs. 200)</label>
</table>
<p><label>Repair: Rs. <input type="text" name="total" value="0" readonly="readonly" /></label></p>
<p><label>Glass: Rs. <input type="text" name="total1" value="0" readonly="readonly" /></label></p>
<p><label>Total: Rs. <input type="text" name="total2" value="0" readonly="readonly" /></label></p>
</fieldset>
</form>
You can do this with the Jquery event Change(). I have added ID names to the input text elements and this Jquery lines:
Check the comments for each line.
$(document).ready(function() {
//HIDE AND SHOW EXTRA OPTIONS
$('.a').hide();
$('#checkb').change(function() {
$('.a').toggle();
});
//CHECK WHEN ANY RADIO INPUT CHANGES
$('fieldset').on('change','input[type=radio]',function(){
//Get the Value and wich field text will change
var value = $(this).attr('value'),
target = $(this).attr('name');
$('#'+target).val(value);
//Show the total
var total = parseInt($('#type').val(),10) + parseInt($('#glass').val(),10);
$('#total').val(total);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<fieldset>
<label>
<input type="radio" name="type" value="200" />Ordinary (Rs. 200)</label>
<br>
<label>
<input type="radio" name="type" value="500" />Original (Rs. 500)</label>
<br>
<input type="checkbox" name="screen" value="yes" id="checkb" />
<label>Do You want a screen guard or a tempered glass?</label>
<br>
<label class="a">
<input type="radio" class="a" name="glass" value="100" />Screen Guard (Rs. 100)</label>
<br>
<label class="a">
<input type="radio" class="a" name="glass" value="200" />Tempered Glass (Rs. 200)</label>
<br>
<p>
<label>Repair: Rs.
<input type="text" id="type" name="total" value="0" readonly="readonly" />
</label>
</p>
<p>
<label>Glass: Rs.
<input type="text" id="glass" name="total1" value="0" readonly="readonly" />
</label>
</p>
<p>
<label>Total: Rs.
<input type="text" id="total" name="total2" value="0" readonly="readonly" />
</label>
</p>
</fieldset>
</form>
You can do it by using a facility given by jquery. Please check the below code
<input type="radio" class="myradio" name="radio" id="r1" data-value="test1"/>
<input type="radio" class="myradio" name="radio" id="r1" data-value="test1"/>
<script type="text/javascript">
var total = 0;
$('.myradio').on('click',function(){
//Here you can get the checkbox value from data-value attribute
alert($(this).data('value');
//Total the Values
total = total + $(this).data('value');
});
</script>
In above code you can easily get the data from checkbox when it is clicked...

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