Javascript - RadioButton, onClick not toggling checkboxes using ONLY native JS - javascript

edit: Contacted the prof; I'm not actually [supposed] to use jQuery on this assignment as the action on the form (e.g. prof's website) doesn't allow for it. Tyvm to all who replied so quickly and helpfully. Therefore, I am interested in a pure, native JS soln. to resolving these difficulties:
getting a group of checkboxes to toggle "on or off" based on whether the user clicks "Yes" or "No" radio button in a DOM-oriented form. Here's the HTML for (I: the radio buttons, II: the checkboxes):
I:) Radio Buttons
<label> Subscribe to our Mailing List? </label>
<input type="radio" name="raydeo" id="rad1" value="Yes" onclick="subscribe()"></input>
<label>Yes</label>
<input type="radio" name="raydeo" id="rad2" value="No" onclick="subscribe()"></input>
<label>No</label>
II.) Checkboxes
<fieldset>
<legend>Mailing List Subscriptions</legend>
<br />
<input type="checkbox" name="mailinglist" value="Corporate Press Release Emails" id="cor"></input><label> Corporate Press Release Emails</label>
<br />
<input type="checkbox" name="mailinglist" value="Upgrade Software Advertising List" id="sof"></input><label> Upgrade Software Advertising List</label>
<br />
<input type="checkbox" name="mailinglist" value="List given to spammers after buyout" id="lspa"></input><label> List given to spammers after buyout</label>
<br />
<input type="checkbox" name="mailinglist" value="The only non-cynical list" id="cyn"></input><label> The only non-cynical list</label>
<br />
<input type="checkbox" name="mailinglist" value="List to sell to spammers" id="tos"></input><label> List to sell to spammers</label>
<br />
<input type="checkbox" name="mailinglist" value="Spam List" id="spal"></input><label> Spam List</label>
<br />
</fieldset>
Using the rationale provided in posts such as Populating Checkboxes Based on Radio Button Click, which still uses jQuery, the best attempt I have made thus far is:
<script>
function subscribe(){
//var yesPlease = document.getElementById("rad1");
//var noThx = document.getElementById("rad2");
var arr = new Array["cor", "sof", "lspa", "cyn", "tos", "spal"];
//var hold = document.getElementById(arr[i]);
//if(hold.getAttribute(arr[i]).checked = true && arr[i] >= 1){
//document.getElementById("cor").innerHTML=hold.getAttribute("checked");
var hold = document.getElementsByName("mailinglist")[0];
for(var i = 0; i < arr.length; i++)
{
if(document.getElementById("rad1").checked==true)
{
hold.getAttribute(arr[i]).checked == true;
}
else if(document.getElementById("rad2").checked==true)
{
hold.getAttribute(arr[i]).checked == false;
}
}
}
</script>
When I load my document and click on either, nothing happens. Here's the screenshot of the concerned section if it helps:thanks:

Remove your inline javascript code and try attaching the event in the js file itself..
Try this
$('#rad1,#rad2').on('click', function() {
$('fieldset input[type="checkbox"]')
.prop('checked',this.value === 'Yes');
}
});
Check Fiddle

You need to an action handler when the radio button is clicked. So that the element attribute "checked" is correctly updated upon clicking.
The code below is edited from yours to just include the click handler on all input type radio
$(document).ready(function(){
function subscribe() {
$('input[type="radio"]').click(function(){
var yesPlease = document.getElementById("rad1");
var noThx = document.getElementById("rad2");
if(yesPlease.checked == true){
//check all boxes
$("#cor").prop("checked", true);
$("#sof").prop("checked", true);
$("#lspa").prop("checked", true);
$("#cyn").prop("checked", true);
$("#tos").prop("checked", true);
$("#spal").prop("checked", true);
}
else if(noThx.checked == true) {
//uncheck all boxes
$("#cor").prop("checked", false);
$("#sof").prop("checked", false);
$("#lspa").prop("checked", false);
$("#cyn").prop("checked", false);
$("#tos").prop("checked", false);
$("#spal").prop("checked", false);
}
});
}
subscribe();
​});​
JSFiddle: http://jsfiddle.net/MSZtx/

This simple code will solve the issue,
JavaScript in HEAD section :
$(document).ready(function(){
$(".radio-button").click(function(){
if($(this).val() == "No")
$(".checkbox-list input").attr("disabled", true);
else
$(".checkbox-list input").attr("disabled", false);
});
})
Also add, the jquery library CDN source before the above code.
Markup in BODY section :
<label> Subscribe to our Mailing List? </label>
<input type="radio" name="raydeo" id="rad1" value="Yes" onclick="subscribe()" class="radio-button"></input><label> Yes</label>
<input type="radio" name="raydeo" id="rad2" value="No" onclick="subscribe()" class="radio-button"></input><label> No</label>
<fieldset class="checkbox-list">
<legend>Mailing List Subscriptions</legend>
<br />
<input type="checkbox" name="mailinglist" value="Corporate Press Release Emails" id="cor"></input><label> Corporate Press Release Emails</label>
<br />
<input type="checkbox" name="mailinglist" value="Upgrade Software Advertising List" id="sof"></input><label> Upgrade Software Advertising List</label>
<br />
<input type="checkbox" name="mailinglist" value="List given to spammers after buyout" id="lspa"></input><label> List given to spammers after buyout</label>
<br />
<input type="checkbox" name="mailinglist" value="The only non-cynical list" id="cyn"></input><label> The only non-cynical list</label>
<br />
<input type="checkbox" name="mailinglist" value="List to sell to spammers" id="tos"></input><label> List to sell to spammers</label>
<br />
<input type="checkbox" name="mailinglist" value="Spam List" id="spal"></input><label> Spam List</label>
<br />
</fieldset>
There is also a 2nd option to do the same task,
JavaScript in HEAD section :
/* Solution - 2 */
function subscribe(ele)
{
if(ele == "No")
$(".checkbox-list input").attr("disabled", true);
else
$(".checkbox-list input").attr("disabled", false);
}
Also add, the jquery library CDN source before the above code.
Changes in MARKUP in body section :
<label> Subscribe to our Mailing List? </label>
<input type="radio" name="raydeo" id="rad1" value="Yes" onclick="subscribe(this.value)" class="radio-button"></input><label> Yes</label>
<input type="radio" name="raydeo" id="rad2" value="No" onclick="subscribe(this.value)" class="radio-button"></input><label> No</label>

Your Code is just working perfectly :- see here:- http://jsfiddle.net/LeWbR/2/
the only problem I could imagine
have you included jquery in your page .
where you have placed your JS function.
see the left hand side dropdown in JSfiddle, if you change the the value from no wrap(body) to
onDomReady or onLoad it won't work.
function subscribe() {
var yesPlease = document.getElementById("rad1");
var noThx = document.getElementById("rad2");
if(yesPlease.checked){
//check all boxes
$("#cor").prop("checked", true);
$("#sof").prop("checked", true);
$("#lspa").prop("checked", true);
$("#cyn").prop("checked", true);
$("#tos").prop("checked", true);
$("#spal").prop("checked", true);
}
else if(noThx.checked) {
//uncheck all boxes
$("#cor").prop("checked", false);
$("#sof").prop("checked", false);
$("#lspa").prop("checked", false);
$("#cyn").prop("checked", false);
$("#tos").prop("checked", false);
$("#spal").prop("checked", false);
}
}
​

Related

How to toggle a radio button with a label

I would like to unselect a radio button when I click on the label and the following code only works as expected if I click on the button itself.
How to link the behaviour of the label to the button?
<label>
<input type="radio" name="choice" value="HTML" onMouseDown="this.__chk = this.checked" onClick="if (this.__chk) this.checked = false" /> Learn HTML
</label>
<label>
<input type="radio" name="choice" value="Java" onMouseDown="this.__chk = this.checked" onClick="if (this.__chk) this.checked = false"/> Learn JavaScript
</label>
Radio buttons don't work like you are thinking they do. To deselect one you need to either select another with the same name attribute or reset the form. The functionality that you are describing fits more with a checkbox than a radio button. See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/radio for the specs. You may also want to take a look at this question/answer: Reset Particular Input Element in a HTML Form.
Also, there is no need to wrap your label tag around the input. The for attribute takes care of the linking.
If you want to de-select a radio button, you will need to reset the form.
form {
display: flex;
flex-direction: column;
}
<form>
<label for="ckb-01">
<input id="ckb-01" type="radio" name="choice" value="HTML" />
Learn HTML
</label>
<label for="ckb-02">
<input id="ckb-02" type="radio" name="choice" value="Java" />
Learn JavaScript
</label>
<label for="ckb-03">
<input id="ckb-03" type="radio" name="choice" value="Java" />
Learn CSS
</label>
<input type="reset" />
</form>
use the attribut for in the label
<label for='idHTML'>Learn HTML </label>
give the radio the id equivalent
<input id='idHTML' type="radio" name="choice" />
what do you mean by this.__chk
onMouseDown="this.__chk = this.checked"
onClick="if (this.__chk) this.checked = false"
if you wanna select just one you could use simply type radio with group the options with one name='choice'
if you want check and uncheck multiple choices you could use checkbox
After many attempts I finally managed to code a working solution with some javascript.
The problem is that as soon as the radio button is clicked its state changes. the previous value needs to be stored in order to know if it has to be unselected or not.
<main id="form">
<label >
<input type="radio" name="rad" id="Radio0" />Learn Html
</label>
<br><br>
<label>
<input type="radio" name="rad" id="Radio1" />Learn CSS
</label>
<br><br>
<label>
<input type="radio" name="rad" id="Radio2" />Learn Java
</label>
</main>
<script>
let buttons = document.querySelectorAll('#form input');
for (button of buttons){
button.dataset.waschecked="false";
button.addEventListener('click', myFunction, false);
}
function myFunction(e) {
if (e.originalTarget.dataset.waschecked == "false"){
for (button of document.querySelectorAll('#form input')){
button.dataset.waschecked = "false";
}
e.originalTarget.dataset.waschecked = "true";
e.originalTarget.checked =true;
}else {
for (button of document.querySelectorAll('#form input')){
button.dataset.waschecked = "false";
}
e.originalTarget.checked =false;
}
}
</script>
Any suggestion to improve this code is welcome.

Is there way to click multiple checkboxes when a option(check box) is on and when it is off you can only select one at a time?

I want to be able to perform the functionality in the picture above. It wont work however.
$("#customSwitches").click(function() {
var $this = $(this);
if ($this.data('clicked')) {
alert("not element clicked");
$this.data('clicked', false);
$(document).on('click', "#radio1, #radio2, #radio3, #radio4").not(this).prop('checked', false);
});
} else {
alert("element clicked");
$this.data('clicked', true);
}
});
In each click of the check box from the groups, you can checked the checked property of #customSwitches. If it is not checked then you can count the length of checked check boxes from the group, if it is more than 1 then you can prevent the default event.
When clicking #customSwitches you can reset all the check boxes from the group.
You can try the following way:
$(".vehicle").click(function(e){
if($('#customSwitches').is(':not(:checked)')){
if($('.vehicle:checked').length > 1){
alert('You can not check multiple');
e.preventDefault();
}
}
});
$("#customSwitches").click(function(e){
$(".vehicle").prop('checked', false);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="customSwitches"> Select Multiple</label><input type="checkbox" id="customSwitches">
<hr/>
<input class="vehicle" type="checkbox" name="vehicle1" value="Bike">
<label for="vehicle1"> I have a bike</label>
<input class="vehicle" type="checkbox" name="vehicle2" value="Car">
<label for="vehicle2"> I have a car</label>
<input class="vehicle" type="checkbox" name="vehicle3" value="Boat">
<label for="vehicle3"> I have a boat</label>
Your current code has some syntax issues and uses nested event handlers, which is not a good design pattern.
In basic terms you are trying to build a dynamic checkbox limiter based on the first checkbox state. To do that simply determine if the first box is checked, and then count the number of checked regions to see if it exceeds the limit. If so, disallow the current box to be checked. Try this:
let $allowMulti = $('#allow_multi').on('change', function() {
if (!this.checked)
$('.region').prop('checked', false); // remove all checks if no multi allowed
});
$('.region').on('change', function() {
let selectedCount = $('.region:checked').length;
if (!$allowMulti.prop('checked') && selectedCount > 1)
$(this).prop('checked', false);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
<label>
<input type="checkbox" id="allow_multi">
Select multiple regions
</label>
</p>
<label>
<input type="checkbox" class="region" value="1"> 1
</label>
<label>
<input type="checkbox" class="region" value="2"> 2
</label>
<label>
<input type="checkbox" class="region" value="3"> 3
</label>
<label>
<input type="checkbox" class="region" value="4"> 4
</label>

Resetting nested radio button selection with cancel button

I have a page where I'm using radio buttons to determine some user options.
Option 1 will have two options within it and Option 2 is stand alone.
The HTML is as follows:
<div>
<input type="radio" name="level0" value="D" id="D" checked="checked" />
<label for="D">D</label>
<div class="sub1">
<div>
<input type="radio" name="level1" value="D0" id="D0" />
<label for="D0">D0</label>
</div>
<div>
<input type="radio" name="level1" value="D1" id="D1" checked="checked" />
<label for="D1">D1</label>
</div>
</div>
<input type="radio" name="level0" value="E" id="E" />
<label for="E">E</label>
<br>
<br>
<button id="cancel-btn" type="button">Cancel</button>
</div>
The problem revolves around the cancel button functionality.
Assuming that the radios with the 'checked' attributes are the default settings, if I start to update these but then decide to not go through with the update and hit the cancel button, I want it to revert to the default settings.
The JavaScript extract that handles this is
$('#E').click(function (event) {
$("#D0").attr('checked', false);
$('#D1').attr('checked', false);
});
$('#D0').click(function (event) {
$('#E').attr('checked', false);
$('#D').attr('checked', true);
});
$('#D1').click(function (event) {
$('#E').attr('checked', false);
$('#D').attr('checked', true);
});
$('#cancel-btn').click(function (event) {
$('input[type=radio]').prop('checked', function () {
return this.getAttribute('checked') == 'checked';
});
});
The problem is that the outer radio buttons are being reset but the inner (D0 and D1) are not.
Thoughts?
Use this in your cancel button code
$('input[type=radio]').attr('checked', false);
$('input[type=radio][default]').attr('checked', true);
This is probably what #billy meant, when he said you should add an arbitrary (in this case "default") attribute

Passing requred attribute on input depending on selection

Hello I am trying to make a javascrip validate option depending on previouse choice.
Here is my form code:
<li><label for="age1">Question One ?</label>
<input type="radio" name="tienes_negocio" value="Yes" class="aboveage1" /> Si
<input type="radio" name="tienes_negocio" value="No" class="aboveage1" /> No</li></ol>
<ol id="parent1" class="formset2">
<li><label for="age2">Question Two ?</label>
<input type="radio" name="labora_negocio" value="Yes" required="true" class="aboveage2" /> Si
<input type="radio" name="labora_negocio" value="No" required="true" class="aboveage2" /> No</li>
Basicaly if you choose No frm the first selections I would like to pass the required attribute inside the selecond selection,
here is the JavaScript code:
$(document).ready(function(){
$("#parent1").css("display","none");
$(".aboveage1").click(function(){
if ($('input[name=tienes_negocio]:checked').val() == "No" ) {
$("#parent1").slideDown("fast"); //Slide Down Effect
$('input[name="labora_negocio"]').prop('required', true);
} else {
$("#parent1").slideUp("fast");
$('input[name="labora_negocio"]').prop('required', false); //Slide Up Effect
}
});
});
this is the code which I am using for passing the requred attribute: $('#labora_negocio').attr('required');
The problem is that when you choose No it is not passing anything.
You have two elements with the same id, in html this is a no no. Also when setting live element states you should set the element property rather than its (html) attribute.
You can select the radio button via their names and set their properties via prop.
<li><label for="age2">Question Two ?</label>
<input type="radio" name="labora_negocio" value="Yes" id="labora_negocio1" class="aboveage2" /> Si
<input type="radio" name="labora_negocio" value="No" id="labora_negocio2" class="aboveage2" /> No</li>
$(".aboveage1").click(function(){
if ($('input[name=tienes_negocio]:checked').val() == "No" ) {
$('[name="labora_negocio"]').prop('required', true);
$("#parent1").slideDown("fast"); //Slide Down Effect
} else {
$('[name="labora_negocio"]').prop('required', false); // not sure about this
$("#parent1").slideUp("fast"); //Slide Up Effect
}
});

Alert if ANY radio options are not checked

I have a form with 3 questions that have 3 radio options each. I want the form to send an alert if ANY of the questions are left blank. This code sends an alert only if ALL of the questions are left blank:
if (!$("input").is(':checked')) {
alert("You left one blank!");
}
So, for example, if I have only one question answered, I want the alert to send. Instead, it continues on with the code.
You have 3 radio groups, so there will be 3 checked inputs and 6 unchecked inputs, I suggest:
if ( $("input[type=radio]:checked").length < 3 ) {
alert('Please answer all of the questions');
}
Try this:
$(document).ready(function () {
$("#btn1").on("click", function () {
var count = 0;
var questions = $("div.question");
questions.each(function () {
if ($(this).find("input").filter('[type="radio"]').filter(":checked").length > 0) {
count++;
}
});
if (count >= questions.length) {
alert("all good");
} else {
alert("something not checked");
}
});
});
With the HTML:
<div class="question">
Question 1:
<input type="radio" name="radio1" />
<input type="radio" name="radio1" />
<input type="radio" name="radio1" />
</div>
<div class="question">
Question 2:
<input type="radio" name="radio2" />
<input type="radio" name="radio2" />
<input type="radio" name="radio2" />
</div>
<div class="question">
Question 3:
<input type="radio" name="radio3" />
<input type="radio" name="radio3" />
<input type="radio" name="radio3" />
</div>
<div>
<input type="button" id="btn1" value="Submit" />
</div>
http://jsfiddle.net/4yQHv/1/
You can change if (count >= questions.length) { to be === instead of >= to make sure exactly 1 radio button is chosen for every question. Otherwise, this allows for more than one radio button to be chosen (which isn't exactly possible when they're grouped by name attribute)...but just wanted to point that out.
http://jsfiddle.net/tVUuW/
<form>
<input type="radio" name="facepunch" class="facepunch" value="1" />
<input type="radio" name="facepunch" class="facepunch" value="2" />
<input type="radio" name="facepunch" class="facepunch" value="3" />
<br />
<input type="radio" name="stack" class="stack" value="1" />
<input type="radio" name="stack" class="stack" value="2" />
<input type="radio" name="stack" class="stack" value="3" />
<br />
<input id="button" type="button">
</form>
$(document).ready(function(){
$('#button').click(function(){
if(!$("input.facepunch:checked").val()) {
alert("Please select facepunch");
}
if(!$("input.stack:checked").val()) {
alert("Please select stack");
}
});
});
If you have only few groups of radios you can use this method, this is one way to validate user data.
I recommend you to check out one of the great jQuery Validation Plugins out there:
jzaefferer plugin, bassistance plugin
Also, Make sure you validate it on the server side as well! The user can send request to your server from somewhere else or even disable javascript on his browser
You can loop through all your radio buttons and see if any of them is unchecked:
$('input[type="radio"]').each(function () {
if( ! $(this).is(':checked') ) {
alert('You left one blank!');
return false; //exit function, so alert won't show multiple times
}
});
Example

Categories

Resources