javascript check radio buttons automatically - javascript

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;
}
});
};

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.

Checkboxes in 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.

Javascript toggle checkbox

I need to toggle all buttons with a single function. Function needs to toggle all checkboxes in the document as my checkboxes are freestanding and not part of a form.
I currently have this, but it is not working properly. I get syntax error: syntax error in my firefox console.
checked=false;
function checkedAll() {
var c = new Array();
c = doc.getElementsByTagName('input');
if (checked == false){
checked = true;
}else{
checked = false;
}
for (var i = 0; i < c.length; i++){
if (c[i].type == 'checkbox'){
c[i].checked = checked;
}
}
}
How can I fix my code?
Thanks
Two main items to refactor. First, instead of doc it must be document. Second instead of relying on a global just pass in a boolean to determine whether or not to check the checkboxes.
function checkedAll(isChecked) {
var c = document.querySelectorAll('input[type="checkbox"]');
for (var i = 0; i < c.length; i++){
c[i].checked = isChecked;
}
}
JS Fiddle: http://jsfiddle.net/Jvnfm/107/
You can alternatively perform the following for each checkbox element:
c[i].click();
This version will trigger any associated event handlers associated with that element.

Javascript check if radio button was checked?

I have found scripts that do it, but they only work with one radio button name, i have 5 different radio button sets. How can i check if its selected right now i tried on form submit
if(document.getElementById('radiogroup1').value=="") {
alert("Please select option one");
document.getElementById('radiogroup1').focus();
return false;
}
does not work.
If you have your heart set on using standard JavaScript then:
Function definition
var isSelected = function() {
var radioObj = document.formName.radioGroupName;
for(var i=0; i<radioObj.length; i++) {
if( radioObj[i].checked ) {
return true;
}
}
return false;
};
Usage
if( !isSelected() ) {
alert('Please select an option from group 1 .');
}
I'd suggest using jQuery. It has a lot of selector options which when used together simplify the much of the code to a single line.
Alternate Solution
if( $('input[type=radio][name=radioGroupName]:selected').length == 0 ) {
alert('Please select an option from group 1 .');
}
var checked = false, radios = document.getElementsById('radiogroup1');
for (var i = 0, radio; radio = radios[i]; i++) {
if (radio.checked) {
checked = true;
break;
}
}
if (!checked) {
alert("Please select option one");
radios.focus();
return false;
}
return true;
A very simple function is:
<script type="text/javascript">
function checkRadios(form) {
var btns = form.r0;
for (var i=0; el=btns[i]; i++) {
if (el.checked) return true;
}
alert('Please select a radio button');
return false;
}
</script>
<form id="f0" onsubmit="return checkRadios(this);">
one<input type="radio" name="r0"><br>
two<input type="radio" name="r0"><br>
three<input type="radio" name="r0"><br>
<input type="submit">
</form>
However, you sould always have one radio button selected by default (i.e. with the select attribute), some user agents may automatically select the first button. Then you just need to check if the default (usually the first one) is checked or not.
Why don't just use a oneliner?
I wrote this code, it will submit the form if at least one radio is checked:
(function(el){for(var i=el.length;i--;) if (el[i].checked) return el[i].form.submit()||1})(document.form_name.radio_name)||alert('please select item')
Otherwise it will make an alert. Or you may also modify it to use with form's onsubmit:
return (function(el){for(var i=el.length;i--;) if (el[i].checked) return 1})(document.form_name.radio_name)||alert('please select item')
Just replace form_name and radio_name accordingly.
See how it works: http://jsfiddle.net/QXeDv/5/
Here's a good tutorial -> http://www.somacon.com/p143.php
// return the value of the radio button that is checked
// return an empty string if none are checked, or
// there are no radio buttons
function getCheckedValue(radioObj) {
if(!radioObj) return "";
var radioLength = radioObj.length;
if(radioLength == undefined)
if(radioObj.checked) return radioObj.value;
else return "";
for(var i = 0; i < radioLength; i++) {
if(radioObj[i].checked) return radioObj[i].value;
}
return "";
}
// set the radio button with the given value as being checked
// do nothing if there are no radio buttons
// if the given value does not exist, all the radio buttons
// are reset to unchecked
function setCheckedValue(radioObj, newValue) {
if(!radioObj) return;
var radioLength = radioObj.length;
if(radioLength == undefined) {
radioObj.checked = (radioObj.value == newValue.toString());
return;
}
for(var i = 0; i < radioLength; i++) {
radioObj[i].checked = false;
if(radioObj[i].value == newValue.toString()) radioObj[i].checked = true;
}
}
Are you ok with jquery? If so:
$(document).ready(function(){
if($('input[type=radio]:checked').length == 0)
{
alert("Please select option one");
document.getElementById('radiogroup1').focus();
return false;
}
}

Checkmark to exclusive item in Javascript

Hi I am using Titanium to create a table of row that can be checked.
I need to write some code in Javascript that allows only one row to be checked and when one is checked the other ones are unchecked.
I am not worried about Titanium part but more about a general solution.
I know I need to setup an array of all the rows. What do I do next when one box is checked? How would I go through the other ones and tell them to become unchecked?
Thanks for your help.
Live example : http://jsfiddle.net/ztm82/
function doit(table, event) {
if (event.target.nodeName === "INPUT"
&& event.target.type === "checkbox"
&& event.target.checked)
{
var rows = table.tBodies[0].rows;
for (var i = 0; i < rows.length; i++)
{
var input = rows[i].getElementsByTagName("INPUT")[0];
if (input !== event.target)
{
input.checked = false;
}
}
}
}
Try something like this:
var checkboxes = document.querySelectorAll('#myTable input[type="checkbox"]'),
checkboxClickHandler,
i;
checkboxClickHandler = function (event) {
var i;
// only uncheck if target is a checkbox which has been checked
if (event.target.checked) {
for (i = 0; i < checkboxes.length; i++) {
// don't uncheck clicked box
if (checkboxes[i] !== event.target) {
checkboxes[i].checked = false;
}
}
}
};
document.getElementById('#myTable').addEventListener('click', checkboxClickHandler, false);
Mutually exclusive checkboxes? Why not use radio buttons (<input type='radio'>) instead? You'd get this behaviour for free and it would be more intuitive for users.

Categories