Javascript check if radio button was checked? - javascript

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

Related

toggle checkbox with javascript

I want to uncheck a checkbox using javascript. I have one button which just unchecks the box and works fine:
function clear() {
document.getElementById("check").checked = "";
}
I have another button that I want to check the box if not checked and uncheck if it is. Below doesn't uncheck the box. I can can switch the if statement and does works the opposite way. What's the problem?
function switchIt() {
if (document.getElementById("check").checked !== "checked") {
document.getElementById("check").checked = "checked";
} else {
document.getElementById("check").checked = "";
}
Thanks!
switch is a reserved word, use another one
function switchIt() {
var box = document.getElementById("check");
if (box.checked) {
box.checked = false;
} else {
box.checked = true;
}
}
setInterval(switchIt, 1000);
<input type="checkbox" id="check" />
Treat "checked" as a boolean, not as a string.
You can just invert it, as in
element = document.getElementById("check")
element.checked = !element.checked
A more featured example:
var $toggle = document.getElementById('toggle');
var $checkbox = document.getElementById('checkbox');
var toggle_checkbox = function() {
$checkbox.checked = !checkbox.checked;
}
$toggle.addEventListener('click',toggle_checkbox);
<label>
Checkbox:
<input id="checkbox" type="checkbox" checked />
</label>
<button id="toggle">Toggle</button>
You need a boolean to do that.
Take a look at this pen:
https://codepen.io/anon/pen/jJyXgO
let checkbox = document.querySelectorAll('#check')[0]
setInterval(function() {
checkbox.checked = !checkbox.checked
}, 1000)
I've never seen it done with a string "checked" before. Try with a boolean like:
function change() {
if (document.getElementById("check").checked !== true) {
document.getElementById("check").checked = true;
} else {
document.getElementById("check").checked = false;
}
}
or easier
function change() {
document.getElementById("check").checked = !document.getElementById("check").checked
}
Don't forget, switch is reserved, so use a different name, as I did with change()

JS: looping function through checkbox array not counting properly

I want to validate the input on a series of checkboxes. There must be at least one checkbox selected, otherwise the user gets an alert to select one. However, the alert appears unless all of the checkboxes are selected.
I realize that the issue is how my for loop params are set, but I cannot figure out how to fix it.
for(var i=0;i<7;i++){
if( !checkboxes[i].checked ){
alert( 'You need to select at least one day!');
checkboxes[i].focus();
return false;
}
}
You can use a flag to set the validation status and set it to true if atleast 1 item is checked.
Then after the loop check whether the flag is set else there are no checkboxes selected.
var valid = false;
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
valid = true;
break;
}
}
if (!valid) {
alert('You need to select at least one day!');
checkboxes[0].focus();
return false;
}
You want to do the opposite of what you're coding. your current code flashes the alert if the current checkbox is not checked, that is, if ANY checkbox is not checked. you can modify it to something like this:
var isChecked = false;
for(var i=0;i<7;i++){
if( checkboxes[i].checked ){
isChecked = true;
}
}
if ( !isChecked ) {
alert( 'You need to select at least one day!');
checkboxes[0].focus();
return false;
}
var clicked = false;
$(".CheckBoxClass").each(function () {
if($(this).checked ) clicked = true;
}
if(clicked)
return true;
else ...

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

Check Input text if empty based upon radio button selected

I have two radiobuttons in a group on my page. Based upon radiobutton selected i want to generate an alert.
var d=GetVal();
function GetVal()
{
var a = null;
var f = document.forms[0];
var e = f.elements["radiogroup"];
for (var i=0; i < e.length; i++)
{
if (e[i].checked)
{
a = e[i].value;
break;
}
}
return a;
}
At the time of form validation, It is always returning only first radiobutton value when iam reading it in if else loop.
if (!checkRadio("form","radiogroup"))
{
alert("none of the option was selected");
return false;
}
//if one radio option was selected
else
{
if(d="firstradiovalue"){
alert("first radio selected");
return false;}
else{
if(d="secondradiovalue"){
alert("second radio Selected");
return false;}
}
}
At the time of form submission, even if i choose second option i only get alert - "first radio selected". Any help. Thx in advance.
You need to use == not =:
if(d == "firstradiovalue"){
alert("first radio selected");
The return value of the expression d = "firstradiovalue" is d itself, which is always true.

How to check/uncheck checkboxes by clicking a hyperlink?

I have 11 checkboxes with individual ids inside a modal popup.I want to have a hyperlink called SelectAll,by clicking on which every checkbox got checked.I want this to be done by javascript/jquery.
Please show me how to call the function
You could attach to the click event of the anchor with an id selectall and then set the checked attribute of all checkboxes inside the modal:
$(function() {
$('a#selectall').click(function() {
$('#somecontainerdiv input:checkbox').attr('checked', 'checked');
return false;
});
});
You can do like this in jquery:
$(function(){
$('#link_id').click(function(){
$('input[type="checkbox"]').attr('checked', 'checked');
return false;
});
});
If you have more than one form, you can specify form id like this:
$(function(){
$('#link_id').click(function(){
$('#form_id input[type="checkbox"]').attr('checked', 'checked');
return false;
});
});
This should work, clicking on the element (typically an input, but if you want to use a link remember to also add 'return false;' to prevent the page reloading/moving) with the id of 'selectAllInputsButton' should apply the 'selected="selected"' attribute to all inputs (refine as necessary) with a class name of 'modalCheckboxes'.
This is un-tested, writing on my phone away from my desk, but I think it's functional, if not pretty.
$(document).ready(
function(){
$('#selectAllInputsButton').click(
function(){
$('input.modalCheckboxes').attr('selected','selected');
}
);
}
);
$(function(){
$('#link_id').click(function(e){
e.preventDefault(); // unbind default click event
$('#modalPopup').find(':checkbox').click(); // trigger click event on each checkbox
});
});
function CheckUncheck(obj) {
var pnlPrivacySettings = document.getElementById('pnlPrivacySettings');
var items = pnlPrivacySettings.getElementsByTagName('input');
var btnObj = document.getElementById('hdnCheckUncheck');
if (btnObj.value == '0') {
for (i = 0; i < items.length; i++) {
if (items[i].type == "checkbox") {
if (!items[i].checked) {
items[i].checked = true;
}
}
}
btnObj.value = "1";
}
else {
for (i = 0; i < items.length; i++) {
if (items[i].type == "checkbox") {
if (items[i].checked) {
items[i].checked = false;
}
}
}
btnObj.value = "0";
}
}

Categories