How to set up groups of checkboxes which affect each other - javascript

Sorry for the ambiguous title, but it's quite hard to condense what I'm trying to do into a few words. Here's exactly what I'm trying to do:
I want to have a series of groups of checkboxes. One would be gender, with checkboxes for Male and Female, one would be Region, with checkboxes for North, East, South and West and so on.
The aim is to allow the user to select say, Male or Female, but as soon as they put a check in a checkbox of another group e.g. any of the Region checkboxes, all of their previous 'checks' from all other groups are removed.
The point is to only allow the user to select from one group of checkboxes at a time.
I can only think of checking which checkboxes have been marked on click using javascript, but was wondering if there was a simpler way which I may be missing.
I've also thought that maybe a hidden radio button for each group could work.
If anyone has a more elegant solution I'm eager to hear it.

Its been a long time since I've done any pure Javascript, libraries like jQuery make this kind of thing so easy. Anyway, something a bit like the following might work, you'd need to test it in a few browsers and tweak to what you need.
<form name="theForm">
<input type="checkbox" id="male" name="theGroup" onClick="clearGroup(this);">male
<input type="checkbox" id="female" name="theGroup" onClick="clearGroup(this);">female
<br />
<input type="checkbox" id="north" name="theGroup" onClick="clearGroup(this);">north
<input type="checkbox" id="south" name="theGroup" onClick="clearGroup(this);">south
<input type="checkbox" id="east" name="theGroup" onClick="clearGroup(this);">east
<input type="checkbox" id="west" name="theGroup" onClick="clearGroup(this);">west
</form>
<script>
function clearGroup(elem) {
var group = document.theForm.theGroup;
for (var i=0; i<group.length; i++) {
if (group[i] != elem) {
group[i].checked = false;
}
}
}
</script>
Here is a working example to play around with.
You could do the equivalent thing in jQuery as simply as
$('input:checkbox').click(function() {
$(this).siblings(':checked').attr('checked', false);
});
and you have no browser compatibility issues to worry about.

Managed to figure it out with a little help from fearofawhack planet. Seems really simple now.
Heres a link to the JSFiddle http://jsfiddle.net/aeeN4/

if you have different groups you can use this code below.
<script>
function clearGroup(elem) {
//alert(elem.name);
var group = document.getElementsByName(elem.name);
for (var i=0; i<group.length; i++) {
if (group[i] != elem) {
group[i].checked = false;
}
}
}
</script>
<form name="theForm">
<input type="checkbox" id="male" name="theGroup2" onClick="clearGroup(this);">male
<input type="checkbox" id="female" name="theGroup2" onClick="clearGroup(this);">female
<br />
<input type="checkbox" id="north" name="theGroup" onClick="clearGroup(this);">north
<input type="checkbox" id="south" name="theGroup" onClick="clearGroup(this);">south
<input type="checkbox" id="east" name="theGroup" onClick="clearGroup(this);">east
<input type="checkbox" id="west" name="theGroup" onClick="clearGroup(this);">west
</form>

Related

get array of checkboxes checked, and only if seletced in a specific order, then go to URL

First time asking here. I tried a number of topics for this, and I currently use a code for checkboxes, but it's for gathering into a mailform and sending to me via php. I can't seem to find exactly what I need for the following scenario.
I am reworking some Flash puzzles to be all html and javascript (or jquery). One puzzle requires the player to enter a code (to open a safe). In Flash they clicked buttons with code symbols on them, so I thought, Checkboxes displayed as images could work...
I have 9 checkboxes. Each has a value from 1 to 9. In the layout they are mixed up (they are not positioned on the page in sequential order) and I use images to represent the checkboxes.
I want to find out if all the boxes are selected, and if they are selected in the exact order of 1-9.
If the checkboxes are checked in the correct order according to their value (1,2,3,4,5,6,7,8,9) then on clicking the Submit button, the player is taken to the next webpage.
I can also do this with names or Ids, whatever works. Or php. I was hoping to keep it simple, because I am not savvy with the javvy. I probably know enough to be dangerous to myself and others :)
Thanks in advance for any help, or links to a topic that could point me in the right direction.
Here's my html code.
<form name="checklist" method="post" action="My-Page.php">
<label>
<input type="checkbox" value="8">
<img src="btn_8.png"></label>
<label>
<input type="checkbox" value="3">
<img src="btn_3.png"></label>
<label>
<input type="checkbox" value="9">
<img src="btn_9.png"></label>
<label>
<input type="checkbox" value="2">
<img src="btn_2.png"></label>
<label>
<input type="checkbox" value="5">
<img src="btn_5.png"></label>
<label>
<input type="checkbox" value="4">
<img src="btn_4.png"></label>
<label>
<input type="checkbox" value="7">
<img src="btn_7.png"></label>
<label>
<input type="checkbox" value="1">
<img src="btn_1.png"></label>
<label>
<input type="checkbox" value="6">
<img src="btn_6.png"></label>
<input type="submit" value="Open">
</form>
Here's the js I found that gets the values, but I don't know how to make it get the values in that specific order, and then go to a URL, or alert the user to an error.
var array = []
var checkboxes = document.querySelectorAll('input[type=checkbox]:checked')
for (var i = 0; i < checkboxes.length; i++) {
array.push(checkboxes[i].value)
}
Update. I struggled with this, and finally asked a friend to help. What took me 8 days, he did in like 1 hour, from scratch.
I do appreciate those who took time to give me some hints, and this site is great for learning.
As you didn't share code , I will not help you fix it. I can give you some hints and you can try to implement that.
Call onClick function on each checkbox selection.
Create an array and push the selected checkbox's values into it.
// example: checkedArr = [1,2,3,4];
maintain a final order of values with another array
// expectedArr = [1,2,3,4];
Deep compare those 2 arrays and depending on their result, proceed with your business logic.
Comparing two array with their order
var is_same_arr = (checkedArr.length == expectedArr.length) && checkedArr.every(function(element, index) {
return element === expectedArr[index];
});
Here is one way to do it in JavaScript. You maintain a selected array that you either add to or remove items from as the checkboxes are clicked. Then, when the form is submitted, you do a couple checks: first you see if all boxes have been checked. Next, you see if all of the numbers in the selected array are in order.
const form = document.querySelector("#form");
let selected = [];
const numberOfCheckboxes = document.querySelectorAll("#form input").length;
form.addEventListener("click", function(e) {
if (e.target.nodeName !== "INPUT") return;
if (e.target.checked) {
selected.push(parseInt(e.target.value));
} else {
selected = selected.filter(el => el != e.target.value);
}
})
function check(e) {
console.log(selected);
if (selected.length !== numberOfCheckboxes) {
e.preventDefault();
alert("You didn't select all the boxes");
}
const inOrder = selected.every((el, i, arr) => i === 0 || el === arr[i-1] + 1);
if (!inOrder) {
e.preventDefault();
alert("Wrong order!");
}
}
<form id="form" onsubmit="return check(event)">
<label>
<input type="checkbox" value="1" /> 1
</label>
<label>
<input type="checkbox" value="2" /> 2
</label>
<label>
<input type="checkbox" value="3" /> 3
</label>
<button>submit</button>
</form>

How to do toggle two mutually exclusive radio buttons in HTML

I have two radio buttons. When I click on one, the other should become unchecked, and vice versa.
The code I've produced so far is not working:
<input type="radio" id="rbdemail" onclick="chekrbdclick()" checked="checked" />
<input type="radio" id="rbdsitelnk" onclick="chekrbdclick()" />
function chekrbdclick()
{
// How to manage here?
}
Simple, just use a 'name' property with the same value for both elements:
<html>
<body>
<form>
<input type="radio" name="size" value="small" checked> Small
<br>
<input type="radio" name="size" value="large"> Large
</form>
</body>
</html>
hope it helps
<form>
<label>
<input type="radio" name="size" value="small" checked> Small
</label>
<br>
<label>
<input type="radio" name="size" value="large"> Large
</label>
</form>
Give them a name attribute with common value like size, and it will work. For best practice, you can place your input tag inside a label tag, so that, even if your user clicks on the text beside the button (ie on "Small" or "Large"), the respective radio button gets selected.
The perfect answer is above answered ,but I wanna share you how it can work by javascript ,this is javascript work (not standard answer) ....
<input type="radio" id="rbdemail" onclick="chekrbdclick(0)" checked="checked" value="Small" />Small<br>
<input type="radio" id="rbdsitelnk" onclick="chekrbdclick(1)" value="Large" />Large
<script>
function chekrbdclick(n)
{
var small = document.getElementById('rbdemail');
var large = document.getElementById('rbdsitelnk');
if(n === 0){
small.checked = true;
large.checked = false;
}
else {
small.checked = false;
large.checked = true;
}
}
</script>

Javascript Checkbox Validation not Checking if Ticked

I've looked through a lot of the questions that people have already asked on this, but I cannot find a solution that has helped me.
I'm a beginner to programming so know little about what to do, I have four check boxes and to submit the form, you have to select at least one of them, but no message comes up and the form is able to be submitted without one of the boxes being ticked.
This is my code below:
<tr>
<td align="right">
<label for="erdbeersocken"><p>Erdbeersocken<sup>*</sup>:</label>
<br>
<label for="armstulpen">Armstulpen<sup>*</sup>:</label>
<br>
<label for="cupcakes">Cupcakes<sup>*</sup>:</label>
<br>
<label for="babykleidung">Babykleidung<sup>*</sup>:</label>
<br>
</td>
<td align="left">
<form action="../" onsubmit="return checkCheckBoxes(this);">
<input type="CHECKBOX" name="CHECKBOX_1" value="Erdbeersocken">
<br>
<input type="CHECKBOX" name="CHECKBOX_2" value="Armstulpen">
<br>
<input type="CHECKBOX" name="CHECKBOX_3" value="Cupcakes">
<br>
<input type="CHECKBOX" name="CHECKBOX_4" value="Babykleidung">
<br>
<input type="SUBMIT" value="Submit!">
</td>
</tr>
</form>
<script type="text/javascript" language="JavaScript">
<!--
function checkCheckBoxes(theForm) {
if (
theForm.CHECKBOX_1.checked == false or
theForm.CHECKBOX_2.checked == false or
theForm.CHECKBOX_3.checked == false or
theForm.CHECKBOX_4.checked == false)
{
alert ('You didn\'t choose any of the checkboxes!');
return false;
} else {
return true;
}
}
//-->
</script>
Which looks like: Text here (Checkbox here)
I'm using Notepadd++ more advanced code does not seem to work, so if anyone could help me with simplified JavaScript, I would really appreciate it. :)
function checkCheckBoxes(theForm) {
if ($("input[type='checkbox']:checked").length){
return true;
}else{
alert ('You didn\'t choose any of the checkboxes!');
return false;
}
}
For your form, you should give all the checkboxes the same name but give each checkbox a different value -- this will create an array for your checkboxes (see note at bottom of response if you don't yet know what an array is):
<input type="CHECKBOX" name="CHECKBOX" value="Erdbeersocken">
<br>
<input type="CHECKBOX" name="CHECKBOX" value="Armstulpen">
<br>
<input type="CHECKBOX" name="CHECKBOX" value="Cupcakes">
<br>
<input type="CHECKBOX" name="CHECKBOX" value="Babykleidung">
then in your confirm submit function you want to use a for loop with two nested if statements to check if a checkbox has been checked. I'll give you an example of some code I recently did:
var interestsSelected = false;
for (var i = 0; i < document.forms[0].interests.length; ++i ) {
if (document.forms[0].interests[i].checked == true) {
interestsSelected = true;
break;
//code gives go ahead for submission because at least one checkbox has been checked
}
}
if (interestsSelected !=true) {
window.alert("You must select at least one hobby or interest");
return false;
//code Woot woot woot! It all works!
}
This was my form section for the checkboxes:
<input type="checkbox" name="interests" value="technology" />Technology <br />
<input type="checkbox" name="interests" value="arts" />The Arts <br />
<input type="checkbox" name="interests" value="music" />Music <br />
<input type="checkbox" name="interests" value="film" />Movies <br/>
<input type="checkbox" name="interests" value="shopping" />Shopping <br />
<input type="checkbox" name="interests" value="outdoor" />Camping <br />
<input type="checkbox" name="interests" value="garden" />Gardening <br />
As a fellow beginner :) I often find it useful if everything is spelled out in as simple a language as possible so I'm going to provide some details here that you might or might not already know.
Anytime you create a form, an array for the form is automatically created (you won't see it listed anywhere, the browser will automatically create one when it accesses the form data BUT you can (should) refer to it in your coding). So if you have one form on your page you will have an array forms[0], if you have two different forms on your page then the first form will have an array forms[0] and the second form will have an array forms[1], each containing all of the elements in the respective forms.
If you name all your checkboxes the same name, you are essentially creating an array within an array -- the big Mama Bear array is forms[0] and nestled inside her is the Baby Bear array (your checkbox name[]).
In order to reference the Baby Bear array, you have to acknowledge the Mama Bear array first: that is why in the code example I gave above, you see "document.forms[0]" (the Mama Bear array) followed by ".interests[i]" (the Baby Bear array).
Hope this helps :)
HTML for my example
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<p>Select a box</p>
<form id="aform">
<input type="checkbox">
<input type="checkbox">
</form>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="test.js"></script>
</body>
</html>
And the javascript in its own file (always seperate code from css and from html)
window.onload=function() {
$("#aform").change(function () {
alert('a box is checked');
})
};

More efficient way to use document.getElementById for checkboxes?

This section of code uses jQuery to hide/show form fields. When they are hidden the values of those fields are set to empty. This is easy for an input field with its unique ID. I run into trouble with checkboxes. The code below works for three checkboxes. But I have to use this same technique for a set of 26 checkboxes. How can I do this more efficiently?
$(".transfer").click(function(){
if ($('input[name=transfer_position]:checked').val() == "yes" ) {
//Slide Down Effect
$(".transfer_details").slideDown("slow");
document.getElementById('transfer_interest').focus();
} else {
//Slide Up Effect
$(".transfer_details").slideUp("slow");
document.getElementById('transfer_interest').value = "";
document.getElementById('select_positions_0').checked = false;
document.getElementById('select_positions_1').checked = false;
document.getElementById('select_positions_2').checked = false;
}
});
<li>
<label>
<input type="radio" name="transfer_position" class="transfer" value="yes" id="transfer_position_0" />
Yes</label>
<label>
<input type="radio" name="transfer_position" class="transfer" value="no" id="transfer_position_1" />
No</label>
</li>
<li class="transfer_details">
<label for="transfer_interest">Why are you interested in transferring to your selected SL positions and what would you bring to that position(s) and team(s)?</label>
<textarea name="transfer_interest" id="transfer_interest" cols="80" rows="6"> </textarea>
</li>
<li class="transfer_details">
<label>
<input type="checkbox" name="select_positions[]" class="select_positons" value="Resident Advisor" id="select_positions_0" />
Resident Advisor</label>
<label>
<input type="checkbox" name="select_positions[]" class="select_positons" value="Programming Assistant" id="select_positions_1" />
Programming Assistant</label>
<label>
<input type="checkbox" name="select_positions[]" class="select_positons" value="Social Justice Advocate " id="select_positions_2" />
Social Justice Advocate </label>
</li>
Use classes, since many elements can share a class. So you simply uncheck all checkboxes with a certain class:
$('.select_positions').attr('checked', false);
Use the amazing power of jquery's selectors, of course!
$('li.transfer_details input[type=checkbox]').prop("checked", false);
descendant selector - http://api.jquery.com/descendant-selector/
setting the checked attribute -
http://api.jquery.com/prop/
One approach would be to use the child selector in conjunction with the checkbox selector, and iterating using the each function in jQuery to accomplish what you're looking for.
Keep in mind this is untested, so its probably going to raise errors and I trust you to fix that.
Beneath your slide up effect, you'd want something like the following:
$('.transfer_details > input:checkbox').each(function() {
(this).checked = false;
});
Hope this helps and happy coding!

How do I deselect a whole group of radio buttons when a user clicks on some other button?

Let's say I have a form where people can choose what kind of pet they want and - optionally - indicate a breed and age like this:
<input type="radio" name="pet" value="P70" /> Cat<br>
Breed:<br>
<input type="radio" name="catbreed" value="P71" /> Persian
<input type="radio" name="catbreed" value="P72" /> Siamese
<input type="radio" name="catbreed" value="P73" /> Tabby <br>
Age:<br>
<input type="radio" name="catage" value="P74" /> Kitten
<input type="radio" name="catage" value="P75" /> Adult
<p>
<input type="radio" name="pet" value="P78" /> Dog<br>
Breed:<br>
<input type="radio" name="dogbreed" value="P79" /> German Shepherd
<input type="radio" name="dogbreed" value="P80" /> Golden Retriever
<input type="radio" name="dogbreed" value="P81" /> Poodle <br>
Age:<br>
<input type="radio" name="dogage" value="P82" /> Puppy
<input type="radio" name="dogage" value="P83" /> Adult
If they first choose "cat" and then switch to "dog," the radio buttons will take care of that. But if they've already selected a breed or age for the cat, there's no way to deselect that. (And they're already 70 questions into the form, so resetting the whole thing is a hassle.)
How can I add a javascript that will deselect the breed and age for one pet if users change their minds and switch to a different pet?
UPDATE: I probably wasn't clear enough in my question. I'm not looking to add a button to reset the breed and age values, I just want it to be automatic and idiot-proof. Clicking "cat" should erase any values that might be there for dogbreed or dogage, and clicking "dog" should erase any values that are there for catbreed or catage.
Since all your questions seem to have unique values, the easiest way would be to make all the cat and dog breeds the same name, like "animalbreed", and do something similar with "animalage".
This might require some rearranging on the backend, but it would solve your frontend problem in the easiest way.
This is totally brute force. Gets all inputs, and in a loop if named catbreed, dogbreed, catage, or dogage, deslects them. It could be refined by only looping over the inputs with type radio.
function clearRadioButtons() {
var inputs = document.getElementsByTagName("input");
var numInputs = inputs.length;
for (i = 0; i < numInputs; i++) {
if (inputs[i].name == "catbreed" || inputs[i].name == "dogbreed" || inputs[i].name == "catage" || inputs[i].name == "dogage") {
inputs[i].selected = false;
}
}
}
<button id='whatever' onclick='clearRadioButtons()'>Clickme</button>
See it in action on jsfiddle

Categories

Resources