Radio Boxes in JavaScript and string manipulation - javascript

wondering if anyone can help with my code. I've been trying to get it to work all day and I have no Idea why the code isn't working :(. So the code is supposed to help the user pick a characters in a game to code with 4 questions. The user inputs there answer via radio buttons.
This is the HTML:
<h2> What Champion Should You Play?</h2>
<h3>
What Lane do You Want to Play?
</h3>
<form onsubmit="getImg()" method="post">
<p> Top </p> <img src="http://img10.deviantart.net/d268/i/2014/226/e/a/gnar__by_dukeofdunkshire-d7v6rgm.jpg"> <input type="radio" name="Lane" value="Top" id="11">
<p> Mid </p><img src="http://www.solomidcdn.com/images/champions/velkoz.png"><input type="radio" name="Lane" value="Mid" id="12">
<p> Jungle</p><img src="https://pbs.twimg.com/media/CF4vu3ZW0AEwR0M.png"><input type="radio" name="Lane" value="Jungle" id="13">
<p> ADC</p><img src="http://img.dwstatic.com/huyaedg/img/hero/Caitlyn.png"><input type="radio" name="Lane" value="Adc" id="14">
<p> Support</p><img src="http://i.imgur.com/2kwycth.png"> <input type="radio" name="Lane" value="Support">
<h3>
What Role do You Want to Play?
</h3>
<p>Assassin</p> <img src="http://vignette3.wikia.nocookie.net/leagueoflegends/images/3/39/Assassin_icon.jpg/revision/20140607013330"> <input type="radio" name="Role" value="Assasin" id="21">
<p>Tank</p><img src="http://3.bp.blogspot.com/--M5c7oXkX6A/U4_N5v-mLjI/AAAAAAAAQ6g/hduKMsQwSX4/s1600/profileIcon662.jpg"> <input type="radio" name="Role" value="Tank" id="22">
<p>Bruiser</p><img src="http://4.bp.blogspot.com/-ZGQQg_79y48/U4-_zTlXL3I/AAAAAAAAQ4g/wnwOyxJ_Ml0/s1600/profileIcon658.jpg"> <input type="radio" name="Role" value="Bruiser" id= "23">
<p>Marksman</p><img src="http://3.bp.blogspot.com/-nT8UdY4SZao/U4-_zr_SKQI/AAAAAAAAQ4o/suUj5L2NmFc/s1600/profileIcon660.jpg"> <input type="radio" name="Role" value="Marksman" id= "24">
<p>Mage</p><img src="http://3.bp.blogspot.com/-pL_H0M6kCtM/U4-_zXyUA6I/AAAAAAAAQ5A/sFrySjxNBsc/s1600/profileIcon659.jpg"> <input type="radio" name="Role" value="Mage" id="25">
<h3>
Do You Want to Piss People off with Cheese?
</h3>
<p>Yes</p><img src="http://www.clker.com/cliparts/O/k/f/l/4/0/cheese-hi.png"> <input type="radio" name="Cheese" value="Yes" id="31">
<p>No</p><img src="http://assets4.tribesports.com/system/challenges/images/000/023/603/original/20120723031440-no-cheese-for-one-week.jpg"> <input type="radio" name="Cheese" value="No" id="32">
<h3>
Mad Plays or Easy Days?
</h3>
<p> Mad Plays</p><img src="http://pre12.deviantart.net/4280/th/pre/i/2014/012/3/b/chibi_thresh_by_koiyaki-d71x098.png"><input type="radio" name="Plays" value="Yes" id="41">
<p> Easy Days</p><img src="http://img3.wikia.nocookie.net/__cb20140807150704/leagueoflegends/images/3/3a/Warwick_Render.png"><input type="radio" name="Plays" value="No" id="42">
<input type="submit" value="Submit">
This is the JavaScript, its supposed to get the answer to the radio buttons, If the radio box is checked it adds '1' to the 'pic' string if not it adds '2'. At the end its supposed to open a window with 'pic' in between 2 strings to form a URL. If I put 'window.open' in the first for loop's else bracket it works for the first 5 numbers (opens 4 tabs).
function getImg()
{
var radio1 = document.getElementsByName('Lane');
var radio2 = document.getElementsByName('Role');
var radio3 = document.getElementsByName('Cheese');
var radio4 = document.getElementsByName('Plays');
var pic = '';
for (var i = 0; i < 6; i++) {
if (radio1[i].checked) {
pic += '1';
}
else {
pic += '2';
}
}
for (var i2 = 0; i2 < 6; i2++)
{
if(radio2[i2].checked)
{
pic += '1';
}
else {
pic += '2';
}
}
for (var i3 = 0; i3 < 2; i3++)
{
if(radio3[i3].checked)
{
pic += '1';
}
else {
pic += '2';
}
}
for (var i4 = 0; i4 < 2; i4++)
{
if(radio4[i4].checked)
{
pic += '1';
}
else {
pic += '2';
}
}
window.open('http://lmetar.com/' + pic + '.png');
}
Thanks in advance for anyone who is able to help me.

You miscounted the number of radioboxes. Don't count yourself, let the computer do it, that's what they are build for!
function getImg() {
var radio1 = document.getElementsByName('Lane');
var radio2 = document.getElementsByName('Role');
var radio3 = document.getElementsByName('Cheese');
var radio4 = document.getElementsByName('Plays');
var pic = '';
for (var i = 0; i < radio1.length; i++) {
// shortcut for your if...else construct
pic += radio1[i].checked ? '1' : '2';
}
for (var i = 0; i < radio2.length; i++) {
pic += radio2[i].checked ? '1' : '2';
}
for (var i = 0; i < radio3.length; i++) {
pic += radio3[i].checked ? '1' : '2';
}
for (var i = 0; i < radio4.length; i++) {
pic += radio4[i].checked ? '1' : '2';
}
window.open('http://lmetar.com/' + pic + '.png');
}
The function document.getElementsByName() returns a list and you can determine the length of it with LIST.length, here: radioX.length.

Related

When unchecking checkbox output value stays same. How can i fix it?

function diagnose() {
var add = 0;
var age = parseFloat(document.getElementById('myNumber').value);
var table = document.getElementById('table');
var checkboxes = document.getElementsByClassName('addon');
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
add += parseFloat(checkboxes[i].value);
}
}
var p = +add;
var ad = 0;
var checkboxe = document.getElementsByClassName('addon2');
if (age < 3 && p >= 4) {
for (var j = 0; j < checkboxe.length; j++) {
if (checkboxe[j].checked) {
ad += parseFloat(checkboxe[j].value);
}
var a = p + ad;
if (a >= 5) {
document.getElementById('total').innerHTML = "Clininacal diagnosis yes ";
}
}
} else {
document.getElementById('total').innerHTML = " Clininacal diagnosis no";
}
}
document.getElementById('table').addEventListener('change', diagnose);
</head>
<body>
Age: <input type="number" id="myNumber" class="no-spinners">
<div id="table">
https://stackoverflow.com/posts/46125218/edit# <input type="checkbox" name="Neonatal" value="1.0" class="addon">
<label for="Neo">Neo</label></br>
<input type="checkbox" name="F" value="1.0" class="addon">
<label for="Feed">Feed</label></br>
<input type="checkbox" name="W" value="1.0" class="addon">
<label for="Weight">Weight</label></br>
<input type="checkbox" name="Dysmorphic" value="1.0" class="addon">
<label for="Char">Char</label></br>
<input type="checkbox" name="Pub" value="1.0" class="addon">
<label for="Pub">Smally</label></br>
<input type="checkbox" name="Dev" value="1.0" class="addon">
<label for="Dev">Dev</label></br>
<hr>
<input type="checkbox" name="Lethargy" value=".5" class="addon2">
<label for="Lethargy">Lethargy</label></br>
<input type="checkbox" name="Typical" value=".5" class="addon2">
<label for="TypicalBehavior">Typical</label></br>
<input type="checkbox" name="Sleep" value=".5" class="addon2">
<label for="Sleep">Sleep</label></br>
<input type="checkbox" name="Short" value=".5" class="addon2">
<label for="Short">Short</label></br>
<input type="checkbox" name="Hypo" value=".5" class="addon2">
<label for="Hypo">Hypo</label></br>
<input type="checkbox" name="Small" value=".5" class="addon2">
<label for="Small">Small</label></br>
<input type="checkbox" name="Narrow" value=".5" class="addon2">
<label for="Narrow">Narrow</label></br>
<input type="checkbox" name="Esot" value=".5" class="addon2">
<label for="Esot">Esot</label></br>
<input type="checkbox" name="Thick" value=".5" class="addon2">
<label for="Thick">Thick</label></br>
<input type="checkbox" name="Speech" value=".5" class="addon2">
<label for="Speech">Speech</label></br>
<input type="checkbox" name="Skin" value=".5" class="addon2">
<label for="Skin">Skin</label></br>
</div>
<span id="total"></span>
</div>
</body>
So I have this code. Above the line each input has 1 point, under the line each input has .5 point. For right result It needs at least 5 points , but 4 of them must be from 1 point inputs. For example, four 1 point and two .5 point. I got It worked, but when unchecking the checkboxes It still shows the same string. So how can I fix it ?
Thanks.
you just needed to add the else on the inner conditional evaluation as well.
The else:
else {
document.getElementById('total').innerHTML = " Clininacal diagnosis no";
}
The whole code:
function diagnose() {
var add = 0;
var age = parseFloat(document.getElementById('myNumber').value);
var table = document.getElementById('table');
var checkboxes = document.getElementsByClassName('addon');
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
add += parseFloat(checkboxes[i].value);
}
}
var p = +add;
var ad = 0;
var checkboxe = document.getElementsByClassName('addon2');
if (age < 3 && p >= 4) {
for (var j = 0; j < checkboxe.length; j++) {
if (checkboxe[j].checked) {
ad += parseFloat(checkboxe[j].value);
}
var a = p + ad;
if (a >= 5) {
document.getElementById('total').innerHTML = "Clininacal diagnosis yes ";
} else {
document.getElementById('total').innerHTML = " Clininacal diagnosis no";
}
}
} else {
document.getElementById('total').innerHTML = " Clininacal diagnosis no";
}
}
document.getElementById('table').addEventListener('change', diagnose);
The last else block stating the negative answer is reached only when the (age < 3 && p >= 4) condition is not met, so when the positive answer was already reached there's no way to rewrite it - quick and dirty solution is to duplicate the last else after the (a >= 5) condition or store results in a variable and decide the resulting message according to it:
var positive = false;
if (age < 3 && p >= 4) {
for (var j = 0; j < checkboxe.length; j++) {
if (checkboxe[j].checked) {
ad += parseFloat(checkboxe[j].value);
}
var a = p + ad;
if (a >= 5) {
positive = true;
}
}
}
if (positive) {
document.getElementById('total').innerHTML = "Clininacal diagnosis yes ";
}
else {
document.getElementById('total').innerHTML = " Clininacal diagnosis no";
}

Adding up total price of selected items (Javascript)

I ran into a problem. Code is here:
// JavaScript Document
window.totalIt= function() {
var input = document.getElementsByName("product");
var total = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].checked) {
total += 1;
}
}
if(total>=3){
document.getElementById("total").value = "$" + (total*29).toFixed(2);
}
else{
document.getElementById("total").value = "$" + (total*39).toFixed(2);
}
}
window.totalPrisDessert= function() {
var input = document.getElementsByName("dessert");
var total = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].checked) {
total += parseFloat(input[i].value);
}
}
document.getElementById("total").value = "$" + total.toFixed(2);
}
<div id="formular">
<div id="formulartekst">
<form>
<h2 class="formskrift">Order Hot Food</h2>
<p class="kroner">$39 / $29 when 3 or more checked</p>
<input name="product" value="39" type="checkbox" id="p1" onclick="totalIt()" /> Monday
<br>
<input name="product" value="39" type="checkbox" id="p2" onclick="totalIt()" /> Tuesday
<br>
<input name="product" value="39" type="checkbox" id="p3" onclick="totalIt()" /> Wednesday
<br>
<input name="product" value="39" type="checkbox" id="p4" onclick="totalIt()" /> Thursday
<br>
<input name="product" value="39" type="checkbox" id="p5" onclick="totalIt()" /> Friday
<h2 class="formskrift">Dessert</h2>
<p class="kroner">$20 ALWAYS</p>
<input name="dessert" value="20" type="checkbox" id="p6" onclick="totalPrisDessert()"/>
Monday<br>
<input name="dessert" value="20" type="checkbox" id="p7" onclick="totalPrisDessert()"/>
Tuesday<br>
<input name="dessert" value="20" type="checkbox" id="p8" onclick="totalPrisDessert()"/>
Wednesday<br>
<input name="dessert" value="20" type="checkbox" id="p9" onclick="totalPrisDessert()"/>
Thursday<br>
<input name="dessert" value="20" type="checkbox" id="p10" onclick="totalPrisDessert()"/>
Friday<br>
<label>
<br> Total
<input value="$0.00" readonly type="text" id="total" />
</label>
<input type="submit" value="Order">
</form>
</div>
</div>
https://jsfiddle.net/u0y7aoct/2/
When I check the top 5 boxes they add the price in the total box. However if I check any of the below 5 boxes (desserts) the price overwrites. I need the total price showing, but right now they are acting as two different.
Try this updated fiddle
Basically, create a common method which does the total of both
window.totalAll = function()
{
document.getElementById("total").value = (totalIt() + totalPrisDessert()).toFixed(2) ;
}
You dont need to call two different function you can add both values by calling same function and just need to check a condtion whether is it product or dessert.
var grndTotal = 0;
var total1 = 0;
var total2 = 0;
window.totalIt= function(name) {
if(name == "product"){
var input = document.getElementsByName("product");
var total = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].checked) {
total += 1;
}
}
if(total>=3){ total1 = (total*29).toFixed(2);}
else{total1 = (total*39).toFixed(2);}
}
if(name == "dessert"){
var input = document.getElementsByName("dessert");
var total = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].checked) {
total += parseFloat(input[i].value);
}
}
total2 = total.toFixed(2);
}
grndTotal = parseInt(total2) + parseInt(total1);
document.getElementById("total").value = "$"+grndTotal ;
}
This is the updated function that work correctly.
https://jsfiddle.net/VijayDhanvai/hd103j4a/
It's just because you programmed it like this. You made two different function for every one of the case and these functions act separately. What did you expect? :)
You need more something like this:
window.totalIt = function() {
var input = document.getElementsByName("product");
var total = 0;
var count = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].checked) {
count += 1;
}
}
if(count >= 3){
total = count * 29;
} else {
total = count * 39;
}
return total;
}
window.totalPrisDessert = function() {
var input = document.getElementsByName("dessert");
var total = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].checked) {
total += parseFloat(input[i].value);
}
}
return total;
}
window.grandTotal = function() {
var total = totalIt() + totalPrisDessert();
document.getElementById("total").value = "$" + total.toFixed(2);
}
Of course, use the new function grandTotal() in your html.

How to find all possible combinations of radio buttons selection in js?

I have radiobuttons in radio groups. For example:
<!-- A -->
<div>A</div>
<input type="radio" name="A" value="A1" checked="checked" />
<input type="radio" name="A" value="A2" />
<input type="radio" name="A" value="A3" />
<!-- B -->
<div>B</div>
<input type="radio" name="B" value="B1" checked="checked" />
<input type="radio" name="B" value="B2" />
It is required to have one selected radio button in each group. I need to find all possible combinations of radio buttons selection. In my example it is:
A=A1, B=B1
A=A2, B=B1
A=A3, B=B1,
A=A1, B=B2,
A=A2, B=B2,
A=A3, B=B2
How can I do it in JS?
Loop through all the A radio buttons, each time looping (in another loop) through Bs.
var A = document.querySelectorAll("[name='A']");
var B = document.querySelectorAll("[name='B']");
for (var i = 0; i < A.length; i++) {
for (var j = 0; j < B.length; j++) {
console.log('A= ' + A[i].value + ', ' + 'B= ' + B[j].value);
}
}
What's the purpose? What are you going to do with those combinations?
If you just want to find all of the possible combinations, then this should do it:
function combinations(groups, numPerGroup){ //array of groups, number per group
var com = [];
for(var i = 0; i < groups.length; i++){
for(var j = 0; j < numPerGroup; j++){
com += groups[i] + i + "\n";
}
}
return com;
}

Javascript function not outputting into html

I'm very new to Javascript and Jquery and am attempting to use this script externally to calculate the value of a users selections (Radio buttons and Checkboxes) and then output the value of the function into my HTML page (id cost) by pressing a button (id submit). This is what I have so far, I would be very appreciative if someone could help me understand why it isn't working.
function add() {
var val1 = 0;
for (i = 0; i < document.form1."radio-choice-v-1"; i++)
{
if (document.form1."radio-choice-v-1"[i].checked === true)
{
val1 = document.form1."radio-choice-v-1"[i].value;
}
}
var val2 = 0;
for (i = 0; i < document.form2."radio-choice-v-2"; i++)
{
if (document.form2.radio-"choice-v-2"[i].checked === true)
{
val2 = document.form2."radio-choice-v-2"[i].value;
}
}
var val3 = 0;
for (i = 0; i < document.form3."radio-choice-v-3"; i++)
{
if (document.form3."radio-choice-v-3"[i].checked === true)
{
val3 = document."form3.radio-choice-v-3"[i].value;
}
}
var val4 = 0;
for (i = 0; i < document.form4."radio-choice-v-4"; i++)
{
if (document.form4."radio-choice-v-4"[i].checked === true)
{
val4 = document.form4."radio-choice-v-4"[i].value;
}
}
var val5 = 0;
for (i = 0; i < document.form5."radio-choice-v-5"; i++)
{
if (document.form5."radio-choice-v-5"[i].checked === true)
{
val5 = document.form5."radio-choice-v-5"[i].value;
}
}
var val6 = 0;
for( i = 0; i < document.form6."checkselection"; i++ )
{
val6 = document.form6."checkselection"[i].value;
}
$("cost").html(" = " + (val1 + val2 + val3 + val4 + val5 + val6));
}
<form name="form1" id="form1">
<fieldset data-role="controlgroup">
<legend>Please select a case:</legend>
<input id="radio-choice-v-1a" name="radio-choice-v-1" value="40" CHECKED="checked" type="radio">
<label for="radio-choice-v-1a">Choice 1 (£40)</label>
<input id="radio-choice-v-1b" name="radio-choice-v-1" value="45" type="radio">
<label for="radio-choice-v-1b">Choice 2 (£45)</label>
<input id="radio-choice-v-1c" name="radio-choice-v-1" value="140" type="radio">
<label for="radio-choice-v-1c">Choice 3 (£140)</label>
</fieldset>
</form>
<form name="form6" id="form6">
<fieldset data-role="controlgroup">
<legend>Select your extras</legend>
<input type="Checkbox" name="checkselection" id="checkbox-extra-1" value="20">
<label for="checkbox-extra-1"> Selection 1 (£20) (recommended)</label>
<input type="Checkbox" name="checkselection" id="checkbox-extra-2" value="12">
<label for="checkbox-extra-2">Selection 2 (£12)</label>
<input type="Checkbox" name="checkselection" id="checkbox-extra-3" value="4">
<label for="checkbox-extra-3">Selection 3 (£4)</label>
<input type="Checkbox" name="checkselection" id="checkbox-extra-4" value="30">
<label for="checkbox-extra-4">Selection 4 (£30)</label>
</fieldset>
</form>
<form>
<input id="submit" type="button" value="Submit" onclick="add();">
</form>
£<u id="cost"></u>
There where quite a few problems with your code. Please have a look at the working example I created on JSFiddle for you:
http://jsfiddle.net/95SrV/1/
I had to comment out the val2+ because you did not have those other forms in the sample HTML you provided:
Pure JavaScript
var val1 = 0;
for (i = 0; i < document.form1["radio-choice-v-1"].length; i++) {
if (document.form1["radio-choice-v-1"][i].checked === true) {
val1 = document.form1["radio-choice-v-1"][i].value;
}
}
However, if you do want to full use jQuery you could use the following code instead:
Full jQuery
var val1 = 0;
$('[name="radio-choice-v-1"]').each(function() {
currentItem = $(this);
if (currentItem.is(":checked")) {
val1 = currentItem.val();
}
});
Try with this one. Make sure all elements will be available like "radio-choice-v-2".
function add() {
var val1 = 0;
for (var i = 0; i < document.form1["radio-choice-v-1"].length; i++)
{
if (document.form1["radio-choice-v-1"][i].checked === true)
{
val1 = document.form1["radio-choice-v-1"][i].value;
}
}
var val2 = 0;
for (i = 0; i < document.form2["radio-choice-v-2"].length; i++)
{
if (document.form2["radio-choice-v-2"][i].checked === true)
{
val2 = document.form2["radio-choice-v-2"][i].value;
}
}
var val3 = 0;
for (i = 0; i < document.form3["radio-choice-v-3"].length; i++)
{
if (document.form3["radio-choice-v-3"][i].checked === true)
{
val3 = document.form3["form3.radio-choice-v-3"][i].value;
}
}
var val4 = 0;
for (i = 0; i < document.form4["radio-choice-v-4"].length; i++)
{
if (document.form4["radio-choice-v-4"][i].checked === true)
{
val4 = document.form4["radio-choice-v-4"][i].value;
}
}
var val5 = 0;
for (i = 0; i < document.form5["radio-choice-v-5"].length; i++)
{
if (document.form5["radio-choice-v-5"][i].checked === true)
{
val5 = document.form5["radio-choice-v-5"][i].value;
}
}
var val6 = 0;
for( i = 0; i < document.form6["checkselection"].length; i++ )
{
if (document.form6["checkselection"][i].checked === true) //Are you missing check here
val6 += document.form6["checkselection"][i].value; // += added here
}
$("#cost").html(" = " + (val1 + val2 + val3 + val4 + val5 + val6));
}
</script>
<form name="form1" id="form1">
<fieldset data-role="controlgroup">
<legend>Please select a case:</legend>
<input id="radio-choice-v-1a" name="radio-choice-v-1" value="40" CHECKED="checked" type="radio">
<label for="radio-choice-v-1a">Choice 1 (£40)</label>
<input id="radio-choice-v-1b" name="radio-choice-v-1" value="45" type="radio">
<label for="radio-choice-v-1b">Choice 2 (£45)</label>
<input id="radio-choice-v-1c" name="radio-choice-v-1" value="140" type="radio">
<label for="radio-choice-v-1c">Choice 3 (£140)</label>
</fieldset>
</form>
<form name="form6" id="form6">
<fieldset data-role="controlgroup">
<legend>Select your extras</legend>
<input type="Checkbox" name="checkselection" id="checkbox-extra-1" value="20">
<label for="checkbox-extra-1"> Selection 1 (£20) (recommended)</label>
<input type="Checkbox" name="checkselection" id="checkbox-extra-2" value="12">
<label for="checkbox-extra-2">Selection 2 (£12)</label>
<input type="Checkbox" name="checkselection" id="checkbox-extra-3" value="4">
<label for="checkbox-extra-3">Selection 3 (£4)</label>
<input type="Checkbox" name="checkselection" id="checkbox-extra-4" value="30">
<label for="checkbox-extra-4">Selection 4 (£30)</label>
</fieldset>
</form>
<form>
<input id="submit" type="button" value="Submit" onclick="add();">
</form>
£<u id="cost"></u>

Adding form verification in this case

I've got 3 groups of radio buttons and 1 set of check boxes.
How do i check if a radio button is selected in each group of radio buttons and at least one check box is selected? And if not, maybe pop an alert window.
So thats : one radio button needs to be selected from all three groups and one check box (all four are mandatory). I've had no luck with this. Thanks
<html>
<head>
<script type="text/javascript">
function DisplayFormValues()
{
var str = '';
var elem = document.getElementById('frmMain').elements;
for(var i = 0; i < elem.length; i++)
{
if(elem[i].checked)
{
str += elem[i].value+"<br>";
}
}
document.getElementById('lblValues').innerHTML = str;
document.frmMain.reset();
}
</script>
</head>
<body>
<form id="frmMain" name="frmMain">
Set 1
<INPUT TYPE="radio" NAME="r1" value="r1a">
<INPUT TYPE="radio" NAME="r1" value="r1b">
<INPUT TYPE="radio" NAME="r1" value="r1c">
<br>
Set 2
<INPUT TYPE="radio" NAME="r2" value="r2a">
<INPUT TYPE="radio" NAME="r2" value="r2b">
<INPUT TYPE="radio" NAME="r2" value="r2c">
<br>
Set 3
<INPUT TYPE="radio" NAME="r3" value="r3a">
<INPUT TYPE="radio" NAME="r3" value="r3b">
<INPUT TYPE="radio" NAME="r3" value="r3c">
<br>
Check 1
<INPUT TYPE="checkbox" NAME="c1" value="c1a">
<INPUT TYPE="checkbox" NAME="c1" value="c1b">
<INPUT TYPE="checkbox" NAME="c1" value="c1c">
<input type="button" value="Test" onclick="DisplayFormValues();" />
</form>
<hr />
<div id="lblValues"></div>
</body>
</html>
Here's a modified version of your function:
function DisplayFormValues() {
var str = '';
var elem = document.getElementById('frmMain').elements;
var groups = { 'r1': 0, 'r2': 0, 'r3':0, 'c1': 0 };
for (var i = 0; i < elem.length; i++){
if (elem[i].checked) {
var n = elem[i].name;
groups[n] += 1
str += elem[i].value + "<br>";
}
}
document.getElementById('lblValues').innerHTML = groups['r1'] + "/" +
groups['r2'] + "/" + groups['r3'] + "/" + groups['c1'];
document.frmMain.reset();
}
In this function we count how many elements are checked (obviously one for radio button in the same group but you understand the principle and this is flexible) and groups[XXX] is the count (with XXX being the group name).
You can adjust to your needs and add the alert as requested.
You can do this in javascript by writing a lot of code or I strongly recommend using jquery validation plugin. Look at this example: http://jquery.bassistance.de/validate/demo/radio-checkbox-select-demo.html
You can do something like:
<input type="radio" validate="required:true" name="family" value="s" id="family_single" class="error">
Which will require at least one option being selected.
Also, its best to have inline feedback when something is not valid. Having alerts can be really annoying.
var radioCount = 0;
var checkBoxCount = 0;
var currentElement;
for (var i = 0; i < elem.length; ++i) {
currentElement = elem[i];
if (!currentElement.checked)
continue;
if (currentElement.type == "checkbox")
++checkBoxCount;
else if (currentElement.type == "radio")
++radioCount;
}
if (radioCount < 3)
//fail
if (checkBoxCount < 1)
//fail

Categories

Resources