Checkboxes in JavaScript - javascript

I've got a problem. I must create a form with five check-boxes.
The user must select exactly three of the five check-boxes.
At the time of change check-box updates the marker at check-box
When the user presses a fourth element should light up at the red light.
3. When you deselect any item marker when it disappears (is white) and the rest are green.
Here is what I'm done: http://jsfiddle.net/epredator/98TfU/
and some of my code, because I can't post a JSfiddle link without some code in text ;):
function checkGreen() {
if (this.checked && counter >= 3) {
console.log("if test in checkGreen()");
}
}
I've got a problem with point 3, because i don't know how to change red light to green after uncheck one of check-boxes with green light. I spend a lot of time on it. As you can see I am not the master of Javascript and ask you for help, pleas help me :) ... and for the end i must use pure JavaScript (no jQuery). Thanks a lot for help ...

Here is how I would do it. It is cleaner than how you were doing it before. FIDDLE. Keep an array of the checked boxes, and use it to determine which ones should be what color.
(function() {
var checked = [];
document.getElementById("Checkbox1").addEventListener("click",toggle);
document.getElementById("Checkbox2").addEventListener("click",toggle);
document.getElementById("Checkbox3").addEventListener("click",toggle);
document.getElementById("Checkbox4").addEventListener("click",toggle);
document.getElementById("Checkbox5").addEventListener("click",toggle);
function toggle() {
if (this.checked) {
checked.push(this);
} else {
var index = checked.indexOf(this);
var box = checked.splice(index,1)[0];
box.nextElementSibling.className = "white";
}
refresh();
}
function refresh() {
for (var i = 0; i < checked.length; i++) {
if (i < 3) {
checked[i].nextElementSibling.className = "green";
} else {
checked[i].nextElementSibling.className = "red";
}
}
}
}());

For Javascript, you can use below code
<script type="text/javascript">
// method to bind handler
function bindEvent(element, type, handler) {
if (element.addEventListener) {
element.addEventListener(type, handler, false);
} else {
element.attachEvent('on' + type, handler);
}
}
// binding click event to all the checkboxes with name 'choice'
// you can generalize this method
window.onload = function () {
var elements = document.getElementsByName('choice');
if (!elements)
return;
for (var i = 0; i < elements.length; i++) {
var ele = elements[i];
bindEvent(ele, 'click', function () {
changeColor();
});
}
}
// Pass the checkbox name to the function
// taken from stack overflow answer
//http://stackoverflow.com/questions/8563240/how-to-get-all-checked-checkboxes
function getCheckedBoxes(chkboxName) {
var checkboxes = document.getElementsByName(chkboxName);
var checkboxesChecked = [];
// loop over them all
for (var i = 0; i < checkboxes.length; i++) {
// And stick the checked ones onto an array...
if (checkboxes[i].checked) {
checkboxesChecked.push(checkboxes[i]);
}
}
// Return the array if it is non-empty, or null
return checkboxesChecked.length > 0 ? checkboxesChecked : null;
}
// with your other function, you can call this function or club the functionality
function changeColor() {
var elements = document.getElementsByName('choice');
if (!elements)
return;
var selectedCheckBoxes = getCheckedBoxes('choice');
if (selectedCheckBoxes && selectedCheckBoxes.length == 3) {
// set color to green
}
}
</script>
and HTML used as: (note only 'name' property from input element)
<span>
<input type="checkbox" name="choice" id="Checkbox1" />1</span>
<span>
<input type="checkbox" name="choice" id="Checkbox2" />2</span>
<span>
<input type="checkbox" name="choice" id="Checkbox3" />3</span>
<span>
<input type="checkbox" name="choice" id="Checkbox4" />4</span>
<span>
<input type="checkbox" name="choice" id="Checkbox5" />5</span>
You can get all the checked elements and if the count is 3, mark every body with interested color.

Related

How can I remove the last checkbox from an array using vanilla javascript

This is an email preferences form with a bunch of checkboxes (16) to allow users to subscribe/unsubscribe.
I have a collection of checkboxes like this;
var checkboxes = document.querySelectorAll('input[type="checkbox"]');
I have a button which when clicked will select all checkboxes on the page and then deselect the unsubscribeAll checkbox;
getAllButton.addEventListener("click", function () {
selectAll();
});
function selectAll() {
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].type == "checkbox") checkboxes[i].checked = true;
}
// un-check the unsubscribeAll checkbox
unsubscribeAll.checked = false;
}
I have a checkbox which when clicked(checked) will deselect all of the other checkboxes on the page;
var unsubscribeAll = document.getElementById("unsubscribeAll");
unsubscribeAll.addEventListener("click", function () {
// un-check this box if already checked
if (this.checked !== true) {
this.checked = false;
} else {
deselectAll();
}
});
function deselectAll() {
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].type == "checkbox") checkboxes[i].checked = false;
}
unsubscribeAll.checked = true;
}
This is all working perfectly. However, my problem is that if the the unsubscribeAll checkbox is checked and the user then selects a checkbox to subscribe to an email I want to deselect the unsubscribeAll checkbox but I'm struggling to make that happen.
I thought I would be able to run another function that would deselect that checkbox like this;
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener("click", deselectUnsubscribeAll);
}
function deselectUnsubscribeAll() {
if (unsubscribeAll.checked === true) {
unsubscribeAll.checked = false;
}
}
Of course, this doesn't work because unsubscribeAll is included in the checkboxes[] array.
Next, I thought I would be able to create a new array of checkboxes that excluded unsubscribeAll so I tried this because it's the last element in that array;
var unsubscribeAll = document.getElementById("unsubscribeAll");
var getAllButton = document.getElementById("select-all");
var checkboxes = document.querySelectorAll('input[type="checkbox"]');
console.log(checkboxes.length); // 16
var popped = checkboxes.pop(); // Uncaught TypeError: checkboxes.pop is not a function
As you can see, that generates an error but I don't understand why. This seems like clunky code but it almost works.
This is one of the pages that I referenced to solve my problem;
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop#examples
I need some direction please.
You say it's the last element in that array, so why do you loop through the end of array and not using for (var i = 0; i < checkboxes.length - 1; i++)?
And then you can add an event listener separately to that.
You can also use Element.matches() API to check if the clicked checkbox is unsubscribeAll and run appropriate functions accordingly. But the first method is more efficient cause you don't need to check for the element on each click event.

how to un-check Radio Button with single click which is checked by default

I have a radio button which by default comes checked when the page loads ,and user can un_check if he want by single click but its not working in single click .. after three clicks the radio button un_checked.
Please see
JSFIDDLE . in the code the radio button with value 7 comes with checked by default , I can be able to un_check by clicking three times on it.is there any way to un_check it by just single click .Any help is appreciated.
Thank you.
<td style="padding-right:0px;"><input type="radio" name="TEST" onclick=" var allRadios = document.getElementsByName('TEST'); var booRadio; var x = 0; for(x = 0; x < allRadios.length; x++){ allRadios[x].onclick = function() { if (booRadio == this) { this.checked = false; booRadio = null; }else{ booRadio = this; } }; }" value="7" CHECKED> 7</td>
A JQuery solution, if you assing a class radioClass to your radio buttons:
(function () {
$('.radioClass').on('mouseup', function (e) {
var xRadioB = this;
if ($(xRadioB).is(':checked')) {
setTimeout(function () {
$(xRadioB).prop('checked', false);
}, 5);
}
});
})();
JSfiddle Example: https://jsfiddle.net/nfed1f7c/
First of all, I hope this is just for a test and that you will not embed events in your HTML as this will become very hard to manage, very quickly. I've manage to get a version working with some improve JavaScript. While I did not play with this for too long, I suspect there are better ways but that's a good first draft to get the results you desire: https://jsfiddle.net/0kyyfvy6/5/
var radioElements = document.querySelectorAll('input[type=radio]');
for (var iterator = 0; iterator < radioElements.length; iterator++) {
var radioElement = radioElements[iterator];
radioElement.addEventListener('mousedown', function (event) {
if (event.currentTarget.checked) {
var radioElement = event.currentTarget;
setTimeout(function () {
radioElement.checked = '';
}, 100);
}
})
}
I tried to have event.stopImmediatePropagation() and so on instead of the setTimeout but for some reasons it did not work. This seems relatively safe to implement depending on your use case.

ng-change event called for radio buttons that are created using ng-repeat the first time but not for second time

How do you call updateRow method from the onchange of radio button event
When the radio button changes, I need to call the updateRow method every time but it's currently only calling it the first time.
Html:
<div ng-repeat="b in RS_BehaviorActions">
<input id="{{b.name}}" type="radio" name="behavior" value="{{b.name}}" style="padding:10px;" ng-model="selBehaviorVal" ng-change="updateRow(obj, selBehaviorVal)" /><label>{{b.name}}</label>
</div>
js:
//on change of updateRow method need to push radio button value into json
$scope.updateRow = function ( obj, selectedItem) {
$scope.selectedItem = selectedItem;
$scope.existInArray = false;
for (var i = 0; i < $scope.permissionArray.length; i++) {
if ($scope.permissionArray[i].relationShip == $scope.relationShip) {
$scope.existInArray = true;
break;
}
}
if ($scope.existInArray) {
for (var i = 0; i < $scope.permissionArray.length; i++) {
if ($scope.permissionArray[i].relationShip == $scope.relationShip) {
index = i;
break;
}
}
//$scope.permissionArray.splice(index, 1);
$scope.permissionArray[index].behavior = $scope.selectedItem;
}
else {
$scope.permissionArray.push({ "relationShip": $scope.relationShip, "behavior": $scope.selectedItem });
}
console.log($scope.permissionArray);
}
You can try using ng-click instead of using ng-change. If you post a jsFiddle it will be easier to give you an appropriate solution.

Show/hide element without inline Javascript

I am trying to show/hide an element with raw Javascript when a radio button has a specific value. I can get it to work with inline Javascript, but I want to try and do it using the addEventListener method.
Here is my HTML:
<label for="petType">Type of Pet: </label>Cat<input" class="radio" name="petType" type="radio" id="petType" value="cat">Dog<input class="radio" name="petType" id="petType" type="radio" value="dog">Other<input class="radio" name="petType" id="petType" type="radio" value="other">
<label for="state">Breed:</label>
<select id="breed">
<option>Shiba Inus</option>
<option>Pembroke Welsh Corgi</option>
<option>Boxer</option>
<option>English Bulldog</option>
</select>
Here is the Javascript I am using to get it to run while using the inline function, with the handler onchange="asdf(this.value)" in my HTML.
function asdf(x) {
var breed = document.getElementById('breed');
if (dog == "dog") {
breed.style.display = "inline";
}
else {
breed.style.display = "none";
}
}
Here is what I have so far:
function asdf(x) {
var breed = document.getElementById('breed');
if (dog == "dog") {
breed.style.display = "inline";
}
else {
breed.style.display = "none";
}
}
var typeOfPet = getElementsByName('petType');
typeOfPet.addEventListener('change', asdf, false);
Fiddle: http://jsfiddle.net/ePDx9/
Problem #1: dog is never defined. I believe you want to check if the value of the changed element is dog, so you should do this instead:
if (this.value == "dog") {
Problem #2: getElementsByName needs to be called as a method of another object (usually document)
var typeOfPet = document.getElementsByName('petType');
Problem #3: AddEventListener should have a lowercase a. It also can't be applied to a node collection, which getElementsByName returns. You should loop through each element instead.
for(var i = typeOfPet.length; i--;) {
typeOfPet[i].addEventListener('change', asdf, false);
}
Working version: http://jsfiddle.net/nderscore/ePDx9/6/
Try:
function asdf(x) {
var breed = document.getElementById('breed');
if (this.value === "dog") { //Look for this.value for dog.
breed.style.display = "inline";
} else {
breed.style.display = "none";
}
}
var typeOfPet = document.getElementsByName('petType'); //Get the elements by name
for (var i = 0, l = typeOfPet.length; i < l; i++) { //Loop through them
typeOfPet[i].addEventListener('change', asdf, false); //Bind listener to them each of them.
}
Demo
getElementsByName is not a standalone method it needs to be applied on document or element.
getElementsByName returns a node collection (live), so you need to loop though them and apply binding on each of them.
Casing of addEventListener and binding on the element was incorrect.
In order to look for the value of current radio just use this.value and do the comparison

javascript check radio buttons automatically

I wanna check radio buttons automatically: I tried this code but it does not work:
Radio buttons have 3 different values, I wanna select the radio button with value 'clean".
How can I check automatically radio buttons on a webpage?
Thanks!
function getElements()
{
for (i=0; i<document.getElementsByTagName('input').length; i++)
{
//if (document.getElementsByTagName('input')[i].type == 'radio')
if(document.getElementsByTagName('input')[i].type=='radio')
{
//if (document.getElementsByTagName('input')[i].value=='clean')
document.getElementsByTagName('input')[i].click();
}
}
I modified the code as following:
for (i=0; i<document.getElementsByTagName('input').length; i++)
{
if(document.getElementsByTagName('input')[i].type=='radio')
{
if(document.getElementsByTagName('input')[i].value == "clean")
{
document.getElementsByTagName('input')[i].checked =true;
}
}
}
but it is not still working:(
the radio buttons are in a iframe, can it be the reason why the code is not working?
Give your radio buttons "names" would make things a lot easier
<input type="radio" name="myradios" value="clean"/>
<input type="radio" name="myradios" value="somethingelse"/>
var elements = document.getElementsByName('myradios');
for (i=0;i<elements.length;i++) {
if(elements[i].value == "clean") {
elements[i].checked = true;
}
}
Working example : http://jsfiddle.net/Dwzc9/
Updated
getElementsByName doesn't seem to be supported in all IE versions ... so you could use the following based on your original example :
var allElems = document.getElementsByTagName('input');
for (i = 0; i < allElems.length; i++) {
if (allElems[i].type == 'radio' && allElems[i].value == 'clean') {
allElems[i].checked = true;
}
}
Working example : http://jsfiddle.net/Dwzc9/2/
you might try setting the "checked" attribute instead.
var getElements = function()
{
var x = document.getElementsByTagName("input");
var oldname = '';
for(var i = 0; i < x.length; i++)
{
if(x[i].type == 'radio' && x[i].name != oldname && x[i].value == 'clean')
{
x[i].checked = true;
oldname = x[i].name;
}
}
};
The problem with this function is that it will attempt to check all the radio buttons, so if they belong to a group (which is usually the case), only the last radio button from each group will be selected. If that is your intention, then great, otherwise it bears thinking about how to decide which button is selected, and breaking the loop. You can see in the function above that I have decided to select only the first button in the group, by checking the name attribute of the element.
I hope this helps you!
Matt
UPDATE
Another way to handle this, using jQuery, would be:
var getElements = function(){
var oldname = '';
$.each($('input[type="radio"]'), function(){
if($(this).attr('name') != oldname && $(this).val() == 'clean'){
$(this).checked = true;
oldname = this.name;
}
});
};

Categories