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
Related
I have a form that I've been working on for a school project and I can't figure out what's wrong with the JavaScript checkAnswer function. The form and all the buttons work, but when I hit the submit button, all that loads is a blank page. I have tried researching forms but I can't figure out where my code is wrong. Why won't it check anything?
Here is the form from my index.html file:
<script src="CheckForm.js"></script>
<form method="post" action="return checkAnswer(this, '1', 'Correct.html',
'Incorrect.html');" name="quizForm" id="quizForm">
<input type="radio" name="choice" value="1"/>
<script>getMusician(answer1);</script><br/>
<input type="radio" name="choice" value="2"/>
<script>getMusician(answer2);</script><br/>
<input type="radio" name="choice" value="3"/>
<script>getMusician(answer3);</script><br/>
<input type="radio" name="choice" value="4"/>
<script>getMusician(answer4);</script><br/>
<input type="submit" value="Submit"/>
</form>
This is the code from my CheckForm.js file:
function checkAnswer(quizForm, Answer, CorrectPage, IncorrectPage)
{
var i = 0;
var j = null;
for(;i<quizForm.elements.length();i++)
{
if(quizForm.elements[i].value.checked)
j = quizForm.elements[i].value;
}
if(j === null)
{
windows.alert("Please make a selection.");
return false;
}
if(j == Answer)
{
document.location.href = CorrectPage;
}
else
{
document.location.href = IncorrectPage;
}
return false;
}
You shouldn't need a form for this. It looks like you are creating a static site so I would remove the form and the rest you are pretty close with. Here is a working example for you.
Also it looks like you are creating some sort of quiz site. Be aware users can use the developer console to see the correct answer (the first input to checkAnswer() method)- I thought it would be worth mentioning that.
function checkAnswer(answer, correctPage, incorrectPage) {
var i = 0;
var j = null;
var inputs = document.getElementsByClassName('musician');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked)
j = inputs[i].value;
}
if (j == null) {
alert("Please make a selection.");
return false;
}
if (j == answer) {
console.log('CORRECT!')
document.location.href = CorrectPage;
} else {
console.log('incorrect :(')
document.location.href = IncorrectPage;
}
}
<div id="inputContainer">
<input type="radio" name="choice" class="musician" value="1" />musician 1
<br/>
<input type="radio" name="choice" class="musician" value="2" />musician 2
<br/>
<input type="radio" name="choice" class="musician" value="3" />musician 3
<br/>
<input type="radio" name="choice" class="musician" value="4">musician 4
<br/>
</div>
<input type="button" onclick="checkAnswer('1', 'Correct.html',
'Incorrect.html')" value="Submit" />
I'm trying to push the current selected radio button into my array 'pen'. The entire collection is getting pushed. The current selections should be the shape, size, metal. I want to be able to concatenate them into an image url but I keep getting the entire array. How do I just get the current input values?
<h2>Pick a shape</h2>
<label>circle</label>
<input type="radio" name="shapes" value="circle" checked>
<input type="radio" name="shapes" value="square">
<label>square</label>
<input type="radio" name="shapes" value="heart">
<label>heart</label>
<br><br>
<hr>
<h2>Pick a metal</h2>
<input type="radio" name="metals" value="silver" checked>silver
<input type="radio" name="metals" value="bronze">bronze
<br><br>
<hr>
<h2>Pick a size</h2>
<input type="radio" name="size" value="sm">sm
<input type="radio" name="size" value="md" checked>md
<input type="radio" name="size" value="lg">lg
$('input:radio').change(function () {
var c = document.getElementById("controls");
var els = document.getElementsByTagName("input");
var pen = new Array();
//console.log(els);
for (var i = 0; i < els.length; i++) {
if (els[i].type == "radio" && els[i].checked == true) {
pen.push(els); // Should I add 'this'
console.log(pen);
}
console.log(pen[0] + "-" + pen[1] + "-" + pen[2] + ".png");
}
});
you need to add the index pen.push(els[i]); ex:
for (var i = 0; i < els.length; i++) {
if (els[i].type == "radio" && els[i].checked == true) {
pen.push(els[i]); // Should I add 'this'
console.log(pen);
}
}
console.log(pen[0] + "-" + pen[1] + "-" + pen[2] + ".png");
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;
}
Here's my code:
<script type="text/javascript" xml:space="preserve">
function ATHD(f) {
var aa = "I would like help with the following topic(s): "
var bb = "Password Reset "
var cc = "Password Setup "
var dd = "Firmware Upgrade (if applicable) "
var ee = "Local Access Setup "
var ff = "Remote Access Setup "
var gg = "Mobile Access Setup "
var hh = "Recording Schedule Setup "
var ii = "How to playback video "
var jj = "How to convert video "
var kk = "Email Notification Setup "
var ll = "PTZ Setup (if applicable) "
if( f.pr.checked == true) {
f.sup.value = aa + bb;
}
if( f.ps.checked == true) {
f.sup.value = aa + cc;
}
}
</script>
<form><input onclick="ATHD(this.form)" id="1" type="checkbox" name="pr" /> Password Reset<br />
<input onclick="ATHD(this.form)" id="2" type="checkbox" name="ps" /> Password Setup<br />
<input onclick="ATHD(this.form)" id="3" type="checkbox" name="fu" /> Firmware Upgrade (if applicable)<br />
<input onclick="ATHD(this.form)" id="4" type="checkbox" name="la" /> Local Access Setup<br />
<input onclick="ATHD(this.form)" id="5" type="checkbox" name="ra" /> Remote Access Setup<br />
<input onclick="ATHD(this.form)" id="6" type="checkbox" name="ma" /> Mobile Access Setup<br />
<input onclick="ATHD(this.form)" id="7" type="checkbox" name="rss" /> Recording Schedule Setup<br />
<input onclick="ATHD(this.form)" id="8" type="checkbox" name="pb" /> How to playback video<br />
<input onclick="ATHD(this.form)" id="9" type="checkbox" name="cv" /> How to convert video<br />
<input onclick="ATHD(this.form)" id="10" type="checkbox" name="en" /> Email Notification Setup<br />
<input onclick="ATHD(this.form)" id="11" type="checkbox" name="ptz" /> PTZ Setup (if applicable)<br />
<br />
<span style="FONT-WEIGHT: bold">Question</span><span style="COLOR: #ff0000">*</span> (please be specific)<br />
<br />
<textarea style="HEIGHT: 164px; WIDTH: 577px" rows="10" cols="40">
</textarea></p>
<p><button>Continue...</button>
<textarea style="HEIGHT: 164px; DISPLAY: hidden; WIDTH: 577px" rows="10" cols="40" name="sup">
</textarea>
</p>
</form>
Basically, what I am looking to do is to whenever a box is checked, I want the value of the checkbox to be added into a hidden field. I understand that I still need to add the "value=[the value of the checkbox]" in the html code; what I want to allow for is multiple checkboxes to be selected so that multiple items will get added to the textbox.
I understand that one way of doing this would be to be to create if-then statements for every possible variation; this would not be very time effective as there would be thousands of permutations.
I am also trying to figure out if using an array would work to simplify this; I am not really sure how to conceptualize this in the simplest way as I have only been doing javascripting for three weeks. If someone can tell me how to think about this, I would greatly appreciate it. Looking more to learn how to do this so I can contribute to these forums and simplify the process of scripting functions as I do not have a background in coding.
If you can use jQuery, you won't need much code:
You could update the results whenever somebody clicks on a checkbox ($('input').on('click', function() {).
I personally would use <label> elements, but that's just me. You could grab the values by
$('input:checked').each(function() {
values.push($(this).parent().text());
});
Here is a working example: http://jsfiddle.net/HarryPehkonen/zNfju/1/
I have made small changes your dom like removing onclick events and It may solve your problem
var arr = [];
remove_item = function(arr,value){
for(b in arr ){
if(arr[b] == value){
arr.splice(b,1);
break;
}
}
return arr;
}
var inputs = document.getElementsByTagName("input");
for(var i=0;i<inputs.length;i++)
{
if(inputs[i].getAttribute('type') == 'checkbox')
{ inputs[i].addEventListener("change",function() {
if(this.checked)
arr.push(parseInt(this.id));
else
{
remove_item(arr,parseInt(this.id));
}
console.log(arr); document.getElementById("chcbx").value = arr.join(",");
},false);
}
}
and have a look at jsFiddle remove_item
Here's another way of doing it.
// find number of checkboxes (you haven't specified if you
// have a set number or not. If you have a set number, just
// set checkboxCount to whatever number you have.
var checkboxCount = 0;
var inputTags = document.getElementsByTagName('input');
for (var i=0, length = inputTags.length; i<length; i++) {
if (inputTags[i].type == 'checkbox') {
checkboxCount++;
}
}
function ATHD() {
var totalValue = '';
for (var i = 1; i < checkboxCount; i++) {
if (document.getElementById(i).checked)
totalValue += inputTags[i].getAttribute("name") + ';';
}
document.getElementById("hdnValues").value = totalValue;
alert(totalValue);
}
This basically counts all the checkboxes, loops through all, checks if they're checked, gets the value of the name attribute, then appends it to a string which is delimited by ;
jsfiddle: http://jsfiddle.net/mcDvw/
Alternatively, you could set all the values you want into the value attribute of the checkbox and read that instead of having the value in JS variable. e.g.
HTML:
<input onclick="ATHD()" id="1" type="checkbox" name="pr" value="Password Reset" /> Password Reset<br />
<input onclick="ATHD()" id="2" type="checkbox" name="ps" value="Password Setup" /> Password Setup<br />
JS:
function ATHD() {
var totalValue = '';
for (var i = 1; i < checkboxCount; i++) {
if (document.getElementById(i).checked)
totalValue += inputTags[i].value + ';';
}
document.getElementById("hdnValues").value = totalValue;
document.getElementById("showValues").value = totalValue;
}
jsfiddle: http://jsfiddle.net/mcDvw/1/
How would I go about detecting the order in which checkboxes are checked? I have a list of checkboxes on a form, and I need to have users select their first and second choices (but no more). So, given this:
<input name="checkbox1" type="checkbox" value="a1"> Option 1
<input name="checkbox1" type="checkbox" value="a2"> Option 2
<input name="checkbox1" type="checkbox" value="a3"> Option 3
<input name="checkbox1" type="checkbox" value="a4"> Option 4
If someone selects option 2, then option 3, I'd like to have some indicator that option 2 was the first choice, and option 3 was the second choice. Any ideas?
Thanks in advance.
Update:
These are extremely helpful suggestions, thank you. As I test these examples, it's giving me a better idea of how to approach the problem - but I'm still a bit stuck (I'm a JS novice). What I want to do is have these labels change as the checkboxes are checked or unchecked, to indicate which is the first or second selection:
<label id="lblA1"></label><input name="checkbox1" type="checkbox" value="a1"> Option 1
<label id="lblA2"></label><input name="checkbox1" type="checkbox" value="a2"> Option 2
<label id="lblA3"></label><input name="checkbox1" type="checkbox" value="a3"> Option 3
<label id="lblA4"></label><input name="checkbox1" type="checkbox" value="a4"> Option 4
So if someone clicks Option 2, then Option 3, lblA2 will display "First", and lblA3 will display "Second". If someone unchecks Option 2 while Option 3 is still checked, lblA3 becomes "First". Hopefully this makes sense?
Thanks!
If you are using jQuery. Below code is does what you have explained and it is tested.
I have used global variables.
<input name="checkbox1" type="checkbox" value="a1" /> Option 1
<input name="checkbox1" type="checkbox" value="a2" /> Option 2
<input name="checkbox1" type="checkbox" value="a3" /> Option 3
<input name="checkbox1" type="checkbox" value="a4" /> Option 4
<input type="button" value="do" id="btn" />
As shown below, it also handles the situation that user unchecks a choice.
$(document).ready(function () {
var first = "";
var second = "";
$('input[name="checkbox1"]').change(function () {
if ($(this).attr('checked')) {
if (first == "") {
first = $(this).attr('value');
}
else if (second == "") {
second = $(this).attr('value');
}
}
else {
if (second == $(this).attr('value')) {
second = "";
}
else if (first == $(this).attr('value')) {
first = second;
second = "";
}
}
});
$('#btn').click(function () {
alert(first);
alert(second);
});
});
I hope that it will be helpful.
UPDATE [IMPORTANT]:
I have noticed that my previous code was incomplete, for example, if you check a1, then a2, then a3, then uncheck a2; my code was not recognising a3 as second.
Here is the complete solution of your updated problem. I used array this time.
The complete HTML:
<label id="lblA1"></label>
<input name="checkbox1" type="checkbox" value="a1" /> Option 1
<label id="lblA2"></label>
<input name="checkbox1" type="checkbox" value="a2" /> Option 2
<label id="lblA3"></label>
<input name="checkbox1" type="checkbox" value="a3" /> Option 3
<label id="lblA4"></label>
<input name="checkbox1" type="checkbox" value="a4" /> Option 4
The complete Javascript:
$(document).ready(function () {
var array = [];
$('input[name="checkbox1"]').click(function () {
if ($(this).attr('checked')) {
// Add the new element if checked:
array.push($(this).attr('value'));
}
else {
// Remove the element if unchecked:
for (var i = 0; i < array.length; i++) {
if (array[i] == $(this).attr('value')) {
array.splice(i, 1);
}
}
}
// Clear all labels:
$("label").each(function (i, elem) {
$(elem).html("");
});
// Check the array and update labels.
for (var i = 0; i < array.length; i++) {
if (i == 0) {
$("#lbl" + array[i].toUpperCase()).html("first");
}
if (i == 1) {
$("#lbl" + array[i].toUpperCase()).html("second");
}
}
});
});
have 2 javascript variables first and second. whenever a checkbox is checked check if first is null if so assign the checkbox id to it, if first is not null set second.
You could have a change listener and a hidden field. Every time the user selects a checkbox, you add the value. Like so (assuming #parent is the parent element of the boxes):
$('#parent').delegate('input[type=checkbox]', 'change', function() {
if($(this).is(':checked')) {
$('#hidden').val($('#hidden').val() + " " + $(this).val())
}
});
The value of the hidden field would then be something like a2 a3 a1...
This is if you want to process the information at the server side. You can then split the string at the server side and examine it. Of course you have to handle removal and adding of selections.
If you just want to process the values on the client, you can add it to an array:
var selected = [];
$('#parent').delegate('input[type=checkbox]', 'change', function() {
if($(this).is(':checked')) {
selected.push($(this).val());
}
});
Try -
$(document).ready(function(){
var checked_no = 0;
$('input[name="checkbox1"]').change(function(){
alert($('input[name="checkbox1"]').filter(':checked').length);
checked_no = $('input[name="checkbox1"]').filter(':checked').length;
// checked_no acts as a counter for no of checkboxes checked.
});
});
Here you have it, if you want something more sophisticated (e.g. to test when an option is unclicked) you have to do some extra work. Just test this html in your browser:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<script type = "text/javascript">
var checkboxClicks = new Array(2);
function updateClickOrder(checkbox) {
if (checkbox.checked) {
if (checkboxClicks[0] ==null) {
checkboxClicks[0] = checkbox.value;
} else if (checkboxClicks[1] ==null) {
checkboxClicks[1] = checkbox.value;
}
}
document.forms[0].clickOrder.value = checkboxClicks[0] + ", " + checkboxClicks[1];
alert(document.forms[0].clickOrder.value);
//alert("Clicked " + checkbox.value);
}
</script>
</head>
<body>
<form name="testCheckboxClickOrder">
<input name="checkbox1" type="checkbox" value="a1" onchange="updateClickOrder(this);"> Option 1
<input name="checkbox1" type="checkbox" value="a2" onchange="updateClickOrder(this);"> Option 2
<input name="checkbox1" type="checkbox" value="a3" onchange="updateClickOrder(this);"> Option 3
<input name="checkbox1" type="checkbox" value="a4" onchange="updateClickOrder(this);"> Option 4
<input type="hidden" name="clickOrder"/>
</form>
</body>
</html>
This is going to save the order in an array. If you deselect the position is removed. The script will attempt to find the element by its value and remove. If you select again the value is added.
<input type="checkbox" value="v1" />
<input type="checkbox" value="v2" />
<input type="checkbox" value="v3" />
<input type="checkbox" value="v4" />
<textarea id="result"></textarea>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
var userInput = [];
var c = 0;
$("input[type=checkbox]").click(function()
{
if ($(this).attr("checked"))
{
userInput[c] = $(this).val();
++c;
}
else
{
var i = parseInt(userInput.join().indexOf($(this).val())) - 2;
userInput.splice(i, 1);
}
});
$("textarea").click(function()
{
$(this).val("");
for (var i in userInput)
{
$(this).val($(this).val() + " " + userInput[i]);
}
});
</script>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<input name="checkbox1" type="checkbox" id="myCheck" value=" Option 1" onclick="myFunction('Option 1')" /> Option 1
<input name="checkbox1" type="checkbox" id="myCheck2" value=" Option 2" onclick="myFunction2('Option 2')" /> Option 2
<input name="checkbox1" type="checkbox" id="myCheck3" value=" Option 3" onclick="myFunction3('Option 3')" /> Option 3
<input name="checkbox1" type="checkbox" id="myCheck4" value=" Option 4" onclick="myFunction4('Option 4')" /> Option 4
<p id="getValues"></p>
</body>
<script>
var array = [];
function removeA(arr) {
var what, a = arguments, L = a.length, ax;
while (L > 1 && arr.length) {
what = a[--L];
while ((ax= arr.indexOf(what)) !== -1) {
arr.splice(ax, 1);
}
}
return arr;
}
function myFunction(text) {
// Get the checkbox
var checkBox = document.getElementById("myCheck");
// Get the output text
// If the checkbox is checked, display the output text
if (checkBox.checked == true)
{
array.push(text);
}
else
{
removeA(array, text);
}
getValues();
}
function myFunction2(text) {
// Get the checkbox
var checkBox = document.getElementById("myCheck2");
// Get the output text
// If the checkbox is checked, display the output text
if (checkBox.checked == true)
{
array.push(text);
}
else
{
removeA(array, text);
}
getValues();
}
function myFunction3(text) {
// Get the checkbox
var checkBox = document.getElementById("myCheck3");
// Get the output text
// If the checkbox is checked, display the output text
if (checkBox.checked == true)
{
array.push(text);
}
else
{
removeA(array, text);
}
getValues();
}
function myFunction4(text) {
// Get the checkbox
var checkBox = document.getElementById("myCheck4");
// Get the output text
// If the checkbox is checked, display the output text
if (checkBox.checked == true)
{
array.push(text);
}
else
{
removeA(array, text);
}
getValues();
}
function getValues()
{
$("#getValues").html(array.join("<br>"));
}
</script>
</html>