Select all Radio Buttons from different groups with javascript - javascript

I want to know if there is a clever way to select all radio buttons from diferent groups at once.
It's an old site, so i cant use jquery.
This is what I got so far.
I put the code on codepen, its look pretty simple to me, but I think maybe there are some easiest way to achieve the same results.
CodePen
HTML:
<form name="form1">
<input type="radio" name="group1" value="1">Yes<br />
<input type="radio" name="group1" value="0">No<br />
<input type="radio" name="group2" value="1">Yes<br />
<input type="radio" name="group2" value="0">No<br />
<input type="radio" name="group3" value="1">Yes<br />
<input type="radio" name="group3" value="0">No
<br />
<br />
<input type="radio" name="group4" value="1" onclick="selectAll(form1)">All Yes<br />
<input type="radio" name="group4" value="0" onClick="selectAll(form1)" >All No
</form>
JAVASCRIPT:
<script type="text/javascript">
function selectAll(form1) {
var check = document.getElementsByName("group4"),
radios = document.form1.elements;
if (check[0].checked) {
for( i = 0; i < radios.length; i++ ) {
if( radios[i].type == "radio" ) {
if (radios[i].value == 1 ) {
radios[i].checked = true;
}
}
}
} else {
for( i = 0; i < radios.length; i++ ) {
if( radios[i].type == "radio" ) {
if (radios[i].value == 0 ) {
radios[i].checked = true;
}
}
}
};
return null;
}
</script>

Try this.You need to pass current page as an parameter onclick="selectAll(this).like this
<form name="form1">
<input type="radio" name="group1" value="1">Yes<br />
<input type="radio" name="group1" value="0">No<br />
<input type="radio" name="group2" value="1">Yes<br />
<input type="radio" name="group2" value="0">No<br />
<input type="radio" name="group3" value="1">Yes<br />
<input type="radio" name="group3" value="0">No
<br />
<br />
<input type="radio" name="group4" value="1" onclick="selectAll(this)">All Yes<br />
<input type="radio" name="group4" value="0" onClick="selectAll(this)" >All No
</form>
<script type="text/javascript">
function selectAll( check ) {
var radio, i=0;
while( radio=check.form.elements[i++] )
if( radio.type == "radio" && radio.value == check.value )
radio.checked = true;
};
</script>

If you change the onclick to selectAll(this) you can get away with this:
function selectAll( check ) {
var radio, i=0;
while( radio=check.form.elements[i++] )
if( radio.type == "radio" && radio.value == check.value )
radio.checked = true;
};

Related

TypeError: Cannot set properties of undefined (setting 'checked') in javascript

<article id="mission">
<img src="https://blog.kakaocdn.net/dn/TfNOJ/btqNXGzXt1z/1Zlb8W1gitIt6WOPWS7z3k/img.gif" width="100%" />
</article>
<article id="container">
<button></button>
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
</article>
<script src="./main.js"></script>
let inputlist = document.querySelectorAll('input');
let button = document.querySelector('button');
let save = 0;
let num = 0;
button.addEventListener('click',()=>{
for(let i = 0; i< 4; i++){
inputlist[(i+save)%14].checked = true;
}
num++;
if(save-1 != -1){
if(inputlist[(save-1)%14].checked == true){
inputlist[(save-1)%14].checked =false;
}
}
save++;
});
When I run the code, it doesn't work any more than 7-8 clicks.
When you enter the link in the body, the first input element should behave like the image that appears.
But I get the error TypeError: Cannot set properties of undefined (setting 'checked') and it doesn't work anymore.
Why?
You have 13 inputs so it should be mod 13 not 14.
Check the snippet below
let inputlist = document.querySelectorAll('input');
let button = document.querySelector('button');
let save = 0;
let num = 0;
button.addEventListener('click',()=>{
for(let i = 0; i < 4; i++){
inputlist[(i + save) % 13].checked = true;
}
num++;
if(save - 1 !== -1){
if(inputlist[(save - 1) % 13].checked === true){
inputlist[(save - 1) % 13].checked = false;
}
}
save++;
});
<article id="mission">
<img src="https://blog.kakaocdn.net/dn/TfNOJ/btqNXGzXt1z/1Zlb8W1gitIt6WOPWS7z3k/img.gif" width="100%" />
</article>
<article id="container">
<button>Move</button>
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
</article>
Looking at your code, you're using %14, but you only have 12 input elements on the page. When the code is running through the loop you run out of elements. The solution is to either change your %14 to %12 or to add in an additional two input elements.
The other option if you're going to add checkboxes would be to use %inputlist.length. This would avoid needing to count how many input elements in your html file.

Javascript error in getting values from checkboxes

I'm not able to get the value from my checkboxes when each of them is selected alone (i.e. in isolation), except for the last one which works fine.
Could anyone help me figure this out and correct my code?
function showChoices() {
var values = [];
var cbs = document.catalog.colors;
for (var i = 0, cbLen = cbs.length; i < cbLen; i++) {
if (cbs[i].checked) {
values.push(cbs[i].value);
document.getElementById('display').innerHTML = "You selected: " + values.join(', ') + ".";
} else {
document.getElementById('display').innerHTML = "Please select an option.";
}
}
}
<form method="post" name="catalog">
<input type="checkbox" name="colors" value="red" /><span>red</span> <br />
<input type="checkbox" name="colors" value="orange" /><span>orange</span> <br />
<input type="checkbox" name="colors" value="green" /><span>green</span> <br />
<input type="checkbox" name="colors" value="blue" /><span>blue</span> <br />
<input type="button" onclick="showChoices();" value="Submit">
</form>
<br />
<span id='display'></span>
Working Solution
You can write js like this and hope this helps:
function showChoices() {
var values = [];
var cbs = document.catalog.colors;
var cbLen = cbs.length;
for (var i = 0; i < cbLen; i++) {
if (cbs[i].checked) {
values.push(cbs[i].value);
}
}
if (values.length != 0) {
document.getElementById('display').innerHTML = "You selected: " + values.join(', ') + ".";
} else {
document.getElementById('display').innerHTML = "Please select an option.";
}
}
<form method="post" name="catalog">
<input type="checkbox" name="colors" value="red" /><span>red</span> <br />
<input type="checkbox" name="colors" value="orange" /><span>orange</span> <br />
<input type="checkbox" name="colors" value="green" /><span>green</span> <br />
<input type="checkbox" name="colors" value="blue" /><span>blue</span> <br />
<input type="button" onclick="showChoices();" value="Submit">
</form>
<br />
<span id='display'></span>
You are overriding the div#display's innerHTML with the "Please select an option..." text whenever the last iteration of your loop jumps into the else block (meaning the last box isn't checked).
I would check if at least one element is selected, and if not return early from your function. After that, you can simply display the values by joining them together.
function showChoices() {
var values = [];
var cbs = Array.from(document.catalog.colors);
let el = document.getElementById('display');
let checked = cbs.filter(e => e.checked);
if (!checked.length) {
el.innerHTML = 'Please select at least one';
return false;
}
el.innerHTML = `You selected ${checked.map(e => e.value).join(', ')}`;
return false;
}
<form method="post" name="catalog">
<input type="checkbox" name="colors" value="red" /><span>red</span> <br />
<input type="checkbox" name="colors" value="orange" /><span>orange</span> <br />
<input type="checkbox" name="colors" value="green" /><span>green</span> <br />
<input type="checkbox" name="colors" value="blue" /><span>blue</span> <br />
<input type="button" onclick="showChoices();" value="Submit">
</form>
<br />
<span id='display'></span>

I am building multiple checkboxes. I want to add the functionality

I am building multiple checkboxes. I want to add the functionality, where in a group one checkbox only one checkbox should checked with right or wrong value. After selecting all the groups submit button should be enables.After clicking on submit button, value of each group should (right or wrong answer) should be displayed.How should I go about doing that ?
function isChecked(checkbox, sub1) {
document.getElementById(sub1).disabled = !checkbox.checked;
}
$("input:checkbox").on('click', function() {
var $box = $(this);
if ($box.is(":checked")) {
var group = "input:checkbox[name='" + $box.attr("name") + "']";
$(group).prop("checked", false);
$box.prop("checked", true);
//alert("checked");
} else {
$box.prop("checked", false);
}
var bool;
$("input.checkbox").change(function() {
bool = $(".checkbox:not(:checked)").length != 6;
// enable/disable
$("#submitbutton").prop('disabled', bool).addClass('btn');
// $("#submitbutton").removeAttr("disabled", bool).addClass("btn");
//$('#submitbutton').removeClass('btn1').prop(':disabled', bool).addClass('btn');
<!-- alert('right')-->
}).change('color');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="checkbox" class="checkbox checkbox_1" id="button0" name="fooby[0][]" value="chk0" />
<input type="checkbox" class="checkbox checkbox_1" id="button1" name="fooby[0][]" value="chk0" />
<br>
<input type="checkbox" class="checkbox checkbox_1" id="button2" name="fooby[1][]" value="chk1" />
<input type="checkbox" class="checkbox checkbox_1" id="button3" name="fooby[1][]" value="chk2" /><br>
<input type="checkbox" class="checkbox checkbox_1" id="button4" name="fooby[2][]" value="chk3" />
<input type="checkbox" class="checkbox checkbox_1" id="button5" name="fooby[2][]" value="chk4" />
<br>
<input type="checkbox" class="checkbox checkbox_1" id="button6" name="fooby[3][]" value="chk5" />
<input type="checkbox" class="checkbox checkbox_1" id="button7" name="fooby[3][]" value="chk6" />
<br>
<input type="checkbox" class="checkbox checkbox_1" id="button8" name="fooby[4][]" value="chk7" />
<input type="checkbox" class="checkbox checkbox_1" id="button9" name="fooby[4][]" value="chk8" />
<br>
<input type="checkbox" class="checkbox checkbox_1" id="button10" name="fooby[5][]" value="chk9" />
<input type="checkbox" class="checkbox checkbox_1" id="button11" name="fooby[5][]" value="chk10" /> <br>
<input type="submit" value="Submit" id="submitbutton" disabled="disabled" class="btn" />
As specified in the comments you can use RadioButton instead of Checkbox this will handle for your the checking stuffs. However, to enable the submit button you have to do some maths, by verifying if the number of the checked radio buttons is the half of the total number of the radio buttons:
if($("input[type='radio']").length/2==$("input[type='radio']:checked").length)
{
$(".btn").prop("disabled","");
}
Finally, here is a demo:
$("input[type='radio']").on("change",function(){
if($("input[type='radio']").length/2==$("input[type='radio']:checked").length)
{
$(".btn").prop("disabled","");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="radio" class="checkbox checkbox_1" id="button0" name="fooby[0][]" value="chk0" />
<input type="radio" class="checkbox checkbox_1" id="button1" name="fooby[0][]" value="chk0" />
<br>
<input type="radio" class="checkbox checkbox_1" id="button2" name="fooby[1][]" value="chk1" />
<input type="radio" class="checkbox checkbox_1" id="button3" name="fooby[1][]" value="chk2" /><br>
<input type="radio" class="checkbox checkbox_1" id="button4" name="fooby[2][]" value="chk3" />
<input type="radio" class="checkbox checkbox_1" id="button5" name="fooby[2][]" value="chk4" />
<br>
<input type="radio" class="checkbox checkbox_1" id="button6" name="fooby[3][]" value="chk5" />
<input type="radio" class="checkbox checkbox_1" id="button7" name="fooby[3][]" value="chk6" />
<br>
<input type="radio" class="checkbox checkbox_1" id="button8" name="fooby[4][]" value="chk7" />
<input type="radio" class="checkbox checkbox_1" id="button9" name="fooby[4][]" value="chk8" />
<br>
<input type="radio" class="checkbox checkbox_1" id="button10" name="fooby[5][]" value="chk9" />
<input type="radio" class="checkbox checkbox_1" id="button11" name="fooby[5][]" value="chk10" /> <br>
<input type="submit" value="Submit" id="submitbutton" disabled="disabled" class="btn"/>
<FORM NAME=MAIN>
<SCRIPT>
HTML = [];
function PRINT(L, X) { HTML.push(L.split("#").join(X)); }
function FLUSH() { document.write(HTML.join("")); HTML = []; }
COOKIE = "ANSWERS";
function SetCookie(NAME, VALUE) { var E = new Date(); E.setFullYear(E.getFullYear() + 5); document.cookie = NAME + "=" + VALUE + ";Expires=" + E.toGMTString(); }
function GetCookie(NAME) { var i, e, s, K = document.cookie.split(";"); for (i = 0; i < K.length; i++) { for (s = 0; K[i].charCodeAt(s) < 33; s++); e = K[i].indexOf("="); if (K[i].substring(s, e) == NAME) return K[i].slice(++e); } return ""; }
BOX_COLOR = "0033CC";
TEXT_COLOR = "FFFFFF";
ROW_COLORS = "111133 333355".split(" ");
Q = "Do you speak English?|Do you have an Apple iPhone X ?|Do you write JavaScript?|Have you ever caught an alligator?|Did you eat it?|Do you like winter?|Is the earth big?|Zero equals false. Agree?|Does your laptop run on 19 volts?".split("|");
ANSWER = GetCookie(COOKIE);
if (ANSWER && ANSWER != null) ANSWER = ANSWER.split(","); else ANSWER = [];
for (i = ANSWER.length; i < Q.length; i++) ANSWER.push(0);
PRINT("<TABLE CELLSPACING=1 CELLPADDING=7 BGCOLOR=#>", BOX_COLOR);
PRINT("<TR><TD>#True<TD>#False<TD>#Questions", "<FONT COLOR=" + TEXT_COLOR + ">");
for (i = 0; i < Q.length; i++)
{
PRINT("<TR BGCOLOR=#>", ROW_COLORS[i&1]);
PRINT("<TD><CENTER><INPUT "+(ANSWER[i]==1?"CHECKED":"")+" NAME=X#A TYPE=CHECKBOX onClick='K(#, 1);'>", i);
PRINT("<TD><CENTER><INPUT "+(ANSWER[i]==2?"CHECKED":"")+" NAME=X#B TYPE=CHECKBOX onClick='K(#, 2);'>", i);
PRINT("<TD onClick='K(#, 0);'><FONT COLOR="+TEXT_COLOR+">"+(i+1)+". " + Q[i], i);
}
PRINT("</TABLE><P>");
PRINT("<INPUT TYPE=BUTTON VALUE=' Get Answers ' onClick='alert(ANSWER);'>");
PRINT("<INPUT TYPE=BUTTON VALUE=' Delete Answers ' onClick='DeleteAnswers();'>");
PRINT("<INPUT TYPE=BUTTON "+(isComplete()?"":"DISABLED")+" NAME=NEXT VALUE=' NEXT ' onClick='Next();' onMouseOver='CheckAnswers();'>");
FLUSH();
function K(N, V) // Click event handler
{
var A = 1;
if (ANSWER[N] == 1 || (ANSWER[N] == 0 && V == 2)) A = 0;
ANSWER[N] = (A) ? 1 : 2;
eval("document.MAIN.X"+N+"A.checked = A;");
eval("document.MAIN.X"+N+"B.checked = !A;");
CheckAnswers();
SaveAnswers();
}
function isComplete() { for (var i = 0; i < Q.length; i++) if (ANSWER[i] == 0) return 0; return 1; }
function AllowNext() { document.MAIN.NEXT.disabled = false; }
function CheckAnswers() { if (isComplete()) AllowNext(); }
function Next() { location.href = "http://www.msn.com"; }
function SaveAnswers() { SetCookie(COOKIE, ANSWER.join(",")); }
function DeleteAnswers()
{
for (var i = 0; i < Q.length; i++)
{
ANSWER[i] = 0;
eval("document.MAIN.X"+i+"A.checked = false;");
eval("document.MAIN.X"+i+"B.checked = false;");
}
document.MAIN.NEXT.disabled = true;
SetCookie(COOKIE, "");
}
</SCRIPT>

Validation for dynamic radio button,checkbox and text area

I have developed one page,which is contains several questions and answer...there are three types of answer radio button,checkbox and text area... i have to validate these dynamically created questions using javascript...
based on the question type i am getting answer options from database whether it may be a radio button or checkbox or text area...
<input type="radio" id="radio" name="21" value="59"/>
<input type="radio" id="radio" name="22" value="60"/>
<input type="radio" id="radio" name="23" value="61"/>
like same as checkbox and text area....
//try 1
var form = document.getElementById('form1');
var inputs = form.getElementsByTagName('INPUT');
for (var i = 0; i < inputs.length; ++i) {
if (inputs[i].type.toLowerCase == 'radio' && !inputs[i].checked)
return false;
}
return true;
//try 2
var rv = document.getElementsByName("reservation_in");
var ci = -1;
for(var ikj=0; ikj < rv.length; ikj++){
if(rv[ikj].checked) {
ci = ikj;
}
}
if (ci == -1) {
document.getElementById('err_reservation_for').innerHTML="";
document.getElementById('err_reservation_for').innerHTML=
'Please let us know
//Reservation for Inside or Patio.';
return false;
}
//try 3
var radios = document.getElementById('radio');
var formValid = false;
var i = 0;
while (!formValid && i < radios.length) {
if (radios[i].checked)
formValid = true;
i++;
}
if (!formValid)
//document.getElementById('radio_error').innerHTML="";
//document.getElementById('radio_error').innerHTML=
'Please select one answer.';
alert("Please select the answer");
return formValid;
I have some sample code which may help you to understand more.
HTML Code:
<div id="que1" class="que">
xyz is not abc? <br />
<div class="ans">
<input type="radio" name="radioGroup1" id="radio1" />One
<input type="radio" name="radioGroup1" id="radio2" />Two
<input type="checkbox" name="check" id="check1" />Three <br/>
<textarea id="textarea-1"></textarea>
</div>
</div><br />
<div id="que2" class="que">
xyz is not abc? <br />
<div class="ans">
<input type="radio" name="radioGroup2" id="radio3" />One
<input type="radio" name="radioGroup2" id="radio3" />Two
<input type="checkbox" name="check" id="check2" />Three <br />
<textarea id="textarea-2"></textarea>
</div>
</div>
JS Code:
var questions=document.getElementsByClassName("que");
for(var i=0;i<questions.length;i++){
var inputs=questions[i].getElementsByTagName("input");
for(var j=0;j<inputs.length;j++){
if(inputs[j].type=="radio"){
alert("question ID:- "+ questions[i].id+ " radio");
}
if(inputs[j].type=="checkbox"){
alert("question ID:- "+ questions[i].id+ " checkbox");
}
}
var textarea=questions[i].getElementsByTagName("textarea");
for(var k=0;k<textarea.length;k++){
alert("question ID:- "+ questions[i].id+ " Textarea");
}
}
Click here check this fiddle
Radio button validation:
Html:
<form>
<input type="radio" id="21" name="radio" value="59"/>
<input type="radio" id="22" name="radio" value="60"/>
<input type="radio" id="23" name="radio" value="61"/>
</form>
Javascript:
if ( ( form.radio[0].checked == false ) && ( form.radio[1].checked == false ) && ( form.radio[2].checked == false ) ) { alert ( "Please choose one radio button" ); return false; }
If there are many input box then use each..that will iterate just like for loop..
var iz_checked = false;
var is_blank = false;
var is_choose = false;
$('button').on('click', function() {
iz_checked = false;
is_blank = false;
is_choose = false;
$('input[type="radio"]').each(function() {
if ($('input[type="radio"]').is(':checked') == true) {
iz_checked = false;
} else {
iz_checked = true;
}
if ($('textarea')[0].value == "") {
is_blank = true;
}
});
$('input[type="checkbox"]').each(function() {
if ($('input[type="checkbox"]').is(':checked') == true) {
is_choose = false;
} else {
is_choose = true;
}
});
if (is_choose || iz_checked || is_blank) {
alert("Validation err");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="radio" id="21" value="59" />a
<input type="radio" id="22" value="60" />q
<input type="radio" id="23" value="61" />w
<input type="radio" id="1" value="59" />e
<input type="radio" id="2" value="60" />r
<input type="radio" id="3" value="61" />t
<input type="radio" id="29" value="59" />y
<input type="radio" id="80" value="60" />u
<input type="radio" id="7" value="61" />i
<input type="radio" id="8" value="59" />o
<input type="radio" id="0" value="60" />p
<input type="radio" id="1" value="61" />l
</form>
<textarea cols="10" rows="10"></textarea>
<br/>
<input type="checkbox" value="Apples">f
<input type="checkbox" value="Apples">d
<input type="checkbox" value="Apples">s
<input type="checkbox" value="Apples">a
<br/>
<button>
Validate
</button>

Javascript: How to check only one item in checkbox

Please help, I failed to code the checkbox that can only checked 1 item. Any help would be appreciated. Thanks
Html
<input type="checkbox" name="<%=Name %>" onClick="return checkbox(this)" >
Javascript
function checkbox(a) {
var Count = 0;
if (a.checked)
{
Count = Count + 1;
}
if (Count == 2)
{
alert('choose One Please');
return false;
}
}
You are declaring count inside a method hence it will always be initialised to 0 when you click on check box. Hence declare count globally and maintain the count.
var NewCount = 0;// global declaration
function KeepCount(a){
if (a.checked){
NewCount = NewCount + 1;
}else{
NewCount = NewCount - 1;
}
if(NewCount>1){
alert('Pick Just One Please');
return false;
}
}
UPDATE:
Another approach if you don't want to add variable globally:
HTML
Group 1
<input type="checkbox" value="1" name="test[1][]" onclick="addClassCheck(this)"/>
<input type="checkbox" value="1" name="test[1][]" onclick="addClassCheck(this)"/>
<input type="checkbox" value="1" name="test[1][]" onclick="addClassCheck(this)"/>
<br/>
Group 2
<input type="checkbox" value="1" name="test[2][]" onclick="addClassCheck(this)"/>
<input type="checkbox" value="1" name="test[2][]" onclick="addClassCheck(this)"/>
<input type="checkbox" value="1" name="test[2][]" onclick="addClassCheck(this)"/>
JavaScript
function addClassCheck(element){
if(element.checked){
element.classList.add("marked");
}else{
element.classList.remove("marked");
}
if(document.getElementsByClassName("marked").length>1){
alert("Please select only one check box");
element.checked=false;
element.classList.remove("marked");
}
}
Fiddle demo
Group your checkboxs as
<input type="checkbox" class="radio" value="1" name="test[1][]" />
<input type="checkbox" class="radio" value="1" name="test[1][]" />
<input type="checkbox" class="radio" value="1" name="test[1][]" />
<br/>
Group 2
<input type="checkbox" class="radio" value="1" name="test[2][]" />
<input type="checkbox" class="radio" value="1" name="test[2][]" />
<input type="checkbox" class="radio" value="1" name="test[2][]" />
Query
$("input:checkbox").click(function() {
if ($(this).is(":checked")) {
var group = "input:checkbox[name='" + $(this).attr("name") + "']";
$(group).prop("checked", false);
$(this).prop("checked", true);
} else {
$(this).prop("checked", false);
}
});
DEMO

Categories

Resources