`alert` Error When Changing Variable Value - javascript

I have radio buttons that alert a different number depending on which one is selected.
var radioButtons = document.querySelectorAll('input[type=radio]');
var chanceoflive1 = 0;
var user;
function choose(choice){
user = choice;
}
function changechanceoflive1(){
if (user == 'bricks') {
chanceoflive1 = 1;
}
else if (user == 'wood') {
chanceoflive1 =3
}
else if (user == 'stone') {
chanceoflive1 = 2
}
alert(chanceoflive1);
}
<div id="radiobuttons" class="container" name="buttons" align=center>
<h2>I Want my Building to be Made of:</h2>
<ul>
<li>
<input type="radio" id="brick-option" name="material" value="1" onClick="choose('bricks')" checked="checked">
<label for="brick-option">Bricks</label>
<div class="check"></div>
</li>
<li>
<input type="radio" id="wood-option" name="material" value="3" onClick="choose('wood')">
<label for="wood-option">Wood</label>
<div class="check">
<div class="inside"></div>
</div>
</li>
<li>
<input type="radio" id="stone-option" name="material" value="2" onClick="choose('stone')">
<label for="stone-option">Stone</label>
<div class="check">
<div class="inside"></div>
</div>
</li>
</ul>
</div>
<form action="chooseheight.html">
<div class="wrapper">
<button class="button" onClick="changechanceoflive1()" align=center>Submit</button>
</div>
</form>
When I click wood, it alerts 3, which is perfect. When I click stone, it alerts 2, which is great. Although, when I click bricks, it alerts 0. Why?

Change line 2 to be
var chanceoflive1 = 1;
and all will work as expected. The initial radio button is preselected. Without clicking away from bricks and then back to bricks, chanceoflive1 remains as its initial value of 0.

That's because the user haven't actually chosen anything if he doesn't click on any of the checkbox. Since you want to make bricks the default option, you can call choose('bricks') at the end of your script, or just set var user = 'bricks'; in the variable declaration.

Related

check the radio button when click on the li using javascript

I have radio button
Html code:
<input type="radio" class="first" name="bright" checked>
<input type="radio" class="second" name="bright" >
<input type="radio" class="third" name="bright">
<input type="radio" class="four" name="bright">
And i have a nav bar
Html code
<ul class="nav">
<li class="st st1 active" data-cont="first">
<h2 class="inner">وزارة الاستثمار</h2>
</li>
<li class="st st2" data-cont="second">
<h2 class="inner">وزارة التجارة</h2>
</li>
<li class="st st3" data-cont="third">
<h2 class="inner">جهات حكومية اخرى</h2>
</li>
<li class="st st4" data-cont="four">
<h2 class="inner">مكتب هندسي</h2>
</li>
</ul>
These 2 are conected with the data-cont that have the class of the radio button
I want when i click on the li the correct radio button be checked using javascript
I tried to make it using this code in JavaScript
let radio = document.querySelectorAll("input");
let radioArray = Array.from(radio);
let tabs = document.querySelectorAll(".nav li");
let tabsArray = Array.from(tabs);
tabsArray.forEach((ele) => {
ele.addEventListener("click", function (e) {
tabsArray.forEach((ele) => {
ele.classList.remove("active");
});
e.currentTarget.classList.add("active");
document.querySelector(e.currentTarget.dataset.cont).checked = true;
});
});
I try to remove the active class from li and put it on the li where i click then i want the radio button be checked
Any body can help me on this?
the last querySelector is where your code is failing you're not referencing the class for your input it needs to be document.querySelector('.' + e.currentTarget.dataset.cont).checked = true; note the "." prefix
Although that answers your question there is probably more value in pointing out that by changing your html markup to be a little more accessible you can eliminate the need for all of the javascript in your example
e.g.
input:checked + label {
color:Red;
}
<div><input type="radio" id="first" name="bright" checked>
<label for='first'>وزارة الاستثما</label>
</div>
<div>
<input type="radio" id="second" name="bright" >
<label for='second'>وزارة التجارة</label>
</div>
<div>
<input type="radio" id="third" name="bright">
<label for='third'>جهات حكومية اخرى</label>
</div>
<div>
<input type="radio" id="four" name="bright">
<label for='four'>مكتب هندسي</label>
</div>
The use of labels associated with your radio buttons is now significantly more accessible and you can drastically reduce a lot of your markup ( though to be accessible you would need to provide a more meaningful name for for attribute.

WordPress: Allow to only check one checkbox in a fieldset

I'm using Gravity Forms and the quiz add-on to build a survey.
Every question should have only one accepted answer. But all answers should be "correct".
The quiz add-on works in a different way. It allows only one correct answer for radio buttons. I couldn't limit checkboxes to only one answer.
So I guess I have to work with custom JavaScript to allow only one answer or checked box per fieldset.
The fieldset for a question looks like this:
<fieldset id="field_3_1" class="gfield" data-field-class="gquiz-field">
<legend class="gfield_label gfield_label_before_complex">Question 1</legend>
<div class="ginput_container ginput_container_checkbox">
<div class="gfield_checkbox" id="input_3_1">
<div class="gchoice gchoice_3_1_1">
<input class="gfield-choice-input" name="input_1.1" type="checkbox" value="gquiz21dc402fa" id="choice_3_1_1">
<label for="choice_3_1_1" id="label_3_1_1">Answer 1</label>
</div>
<div class="gchoice gchoice_3_1_2">
<input class="gfield-choice-input" name="input_1.2" type="checkbox" value="gquiz3414cb0c0" id="choice_3_1_2">
<label for="choice_3_1_2" id="label_3_1_2">Answer 2</label>
</div>
<div class="gchoice gchoice_3_1_3">
<input class="gfield-choice-input" name="input_1.3" type="checkbox" value="gquiz21d0214b9" id="choice_3_1_3">
<label for="choice_3_1_3" id="label_3_1_3">Answer 3</label>
</div>
</div>
</div>
</fieldset>
It's not clear how many fieldsets/questions are present at the end. So I need a flexible solution.
I found some JS Code here:
$(function () {
$('input[type=checkbox]').click(function () {
var chks = document.getElementById('<%= chkRoleInTransaction.ClientID %>').getElementsByTagName('INPUT');
for (i = 0; i < chks.length; i++) {
chks[i].checked = false;
}
if (chks.length > 1)
$(this)[0].checked = true;
});
});
But I'm not sure how to adapt it for my use case
This script will make each checkbox per fieldset exclusive.
jQuery(function($) {
$('fieldset input[type="checkbox"]').on('change', function() {
// Set the checkbox just checked.
let just_checked = $(this);
// Get all of the checkboxes in the fieldset.
let all_checkboxes = just_checked.closest('fieldset').find('input[type="checkbox"]');
$.each(all_checkboxes, function(i, v) { // Loop through each of the checkboxes.
if (just_checked.prop('id') === $(v).prop('id')) {
// Check the one just checked.
$(v).prop('checked', true);
} else {
// Uncheck the others.
$(v).prop('checked', false);
}
})
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset id="field_3_1" class="gfield" data-field-class="gquiz-field">
<legend class="gfield_label gfield_label_before_complex">Question 1</legend>
<div class="ginput_container ginput_container_checkbox">
<div class="gfield_checkbox" id="input_3_1">
<div class="gchoice gchoice_3_1_1">
<input class="gfield-choice-input" name="input_1.1" type="checkbox" value="gquiz21dc402fa" id="choice_3_1_1">
<label for="choice_3_1_1" id="label_3_1_1">Answer 1</label>
</div>
<div class="gchoice gchoice_3_1_2">
<input class="gfield-choice-input" name="input_1.2" type="checkbox" value="gquiz3414cb0c0" id="choice_3_1_2">
<label for="choice_3_1_2" id="label_3_1_2">Answer 2</label>
</div>
<div class="gchoice gchoice_3_1_3">
<input class="gfield-choice-input" name="input_1.3" type="checkbox" value="gquiz21d0214b9" id="choice_3_1_3">
<label for="choice_3_1_3" id="label_3_1_3">Answer 3</label>
</div>
</div>
</div>
</fieldset>
An alternative solution could be to use radio buttons, and use css to make them look like checkboxes. But UX says that checkboxes shouldn't be used as radio buttons, and vice versa. For whatever that's worth.

Checkboxes not being checked programmatically after user checks it once

I'm having an interesting problem I can't solve with a Vue app I'm working on. The behaviour I want (parent checkbox when (un)checked, (un)checks all child checkboxes) is there, but with a problem.
When you click a checkbox, that checkbox is ignored by parent checkboxes. This means that after clicking any child checkbox, clicking a parent checkbox has no effect on the previously clicked checkbox; it just keeps it's value.
Here's where it gets weird: I looked at the elements tab in safari, and it says the clicked box is changing values when the parent is (un)selected, but visually it is staying the same.
I know that the box is checked, since other parts of the app are doing what I expect, but I can't figure out why it will say a box has class="checked" checked="checked", but still be visually unchecked.
Is there something else that happens to a checkbox when you click it, that makes the way I check child checkboxes visually incorrect?
Relevant HTML:
<template>
<div v-for=“(foo, bar) in foobar” :key=bar>
<div class=“root”>
<input id='checkbox' type="checkbox" class="checked" checked="checked" #click=“handleRootClick($event)">
</div>
<div class=“child 1”>
<div v-for=“(foo, bar) in foobar” :key=bar>
<div class=“child 1 header">
<input id='checkbox' type="checkbox" class="checked" checked="checked" #click=“handleChild1Click($event)">
</div>
<div class=“child 1”>
<div v-if=“foobar.length > 0">
<div class=“child 2 header">
<input id='checkbox' type="checkbox" class="checked" checked="checked" #click=“handleChild2Click($event)">
</div>
<div class="resource-dropdown-contents">
<div v-for=“(foo, bar) in foobar” :key=bar>
<div class=“child 3 header">
<input id='checkbox' type="checkbox" class="checked" checked="checked" #click=“handleChild3Click($event)">
</div>
<div class="compute-dropdown-contents">
<div v-for=“(foo, bar) in foobar” :key=bar>
<div class=“child 4 header">
<input id='checkbox' type="checkbox" class="checked" checked="checked" #click=“handleChild4Click($event)">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
And here is the relevant typescript code:
public handleRootClick(e) {
const root = e.currentTarget.parentElement.parentElement;
const checkboxes = root.querySelectorAll('#checkbox');
const isChecked = checkboxes[0].classList.contains('checked');
if (isChecked) {
// ensure all children are unchecked
for (let i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].classList.contains('checked')) {
checkboxes[i].classList.remove('checked');
checkboxes[i].removeAttribute('checked');
}
}
} else {
// ensure all children are checked
for (let i = 0; i < checkboxes.length; i++) {
if (!checkboxes[i].classList.contains('checked')) {
checkboxes[i].classList.add('checked');
checkboxes[i].setAttribute('checked', 'checked');
}
}
}
e.stopPropagation();
}
The other handleChildxClick functions are very similar to the above function.

Allow only one radio button to be selected from multiple groups of checkboxes

I have a number of account items.
I am displaying these in a list doing something like
<md-list-item ng-repeat="item in items">
and for every such item i display three radio buttons in a group, holding values like
admin
user
moderator
Right now a user can select a value for each group of radio buttons, but what I want to do is have only one admin.
So if an admin value is selected the I should block all other admin radio buttons.
How can this be done?
Have a ng-change method that stores the admin item in a scope property to keep track of which item has admin selected:
$scope.radioChanged = function (item) {
if (item.selectedValue == "admin") {
$scope.admin = item;
}
else if (item == $scope.admin) {
$scope.admin = undefined;
}
};
Then use ng-disabled on the admin radio button that will disable the radio button if an admin has been selected and the admin is not the current item.
<div ng-repeat="item in items">
<label><input type="radio" name="{{item.id}}" value="admin" ng-model="item.selectedValue" ng-change="radioChanged(item)" ng-disabled="admin && item != admin"/>admin</label>
<label><input type="radio" name="{{item.id}}" value="user" ng-model="item.selectedValue" ng-change="radioChanged(item)"/>user</label>
<label><input type="radio" name="{{item.id}}" value="moderator" ng-model="item.selectedValue" ng-change="radioChanged(item)"/>moderator</label>
</div>
Plunkr
I would create a variable, maybe adminExists, that is set to true when you select 'Admin' on any of the radio buttons. You could then have all the "Admin" radio buttons become disabled if(adminExists && !isSelected), where isSelected is true if that radio button is the admin button that was selected.
The code below checks the value of the selected radio button against the value of other radio buttons to see if they match up (in this case if the value is "admin"). It then deselects all the radio input elements with that value and then checks the element that was initially clicked or selected to set it to active. You can change the function to use a data attribute instead of the value if you'd prefer as well.
$(".group input[type=radio]").bind("click change keydown focus", function () {
var el = $(this);
var val = el.val();
if (el.prop("checked", true) && val == "admin") {
$(".group input[type=radio]").each(function () {
if ($(this).val() == "admin") $(this).prop("checked", false);
});
el.prop("checked", true);
}
});
.choice {
display:block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
<div class="group">
<div class="choice">
<input type="radio" name="group[0][]" value="admin" />
<label>Admin</label>
</div>
<div class="choice">
<input type="radio" name="group[0][]" value="user" />
<label>User</label>
</div>
<div class="choice">
<input type="radio" name="group[0][]" value="moderator" />
<label>Moderator</label>
</div>
</div>
<div class="group">
<div class="choice">
<input type="radio" name="group[1][]" value="admin" />
<label>Admin</label>
</div>
<div class="choice">
<input type="radio" name="group[1][]" value="user" />
<label>User</label>
</div>
<div class="choice">
<input type="radio" name="group[1][]" value="moderator" />
<label>Moderator</label>
</div>
</div>
</form>

Enable radio button with another radio button

How can I enable child radio buttons when a parent radio button is selected?
<body>
<p>
<input type="radio" id="bdmain" name="educationalqualification" disabled="true" /> Bachelor's Degree
</p>
<ul>
<li>
<label>
<input type="radio" name="bd" disabled="true"/>
Four Years
</label>
</li>
<li>
<label>
<input type="radio"name="bd" disabled="true"/>
Exceeding Four Years
</label>
</li>
</ul>
</body>
Try,
$("#bdmain").parent().next("ul").find("input[type='radio']").each(function(){
$(this).removeAttr("disabled");
});
You'll have to remove disabled="true" from the parent button (I also added a label)
<body>
<p>
<label for="bdmain">
<input type="radio" id="bdmain" name="educationalqualification" />
Bachelor's Degree
</label>
</p>
<ul>
<li>
<label>
<input type="radio" name="bd" class="bdmain-child" disabled="true"/>
Four Years
</label>
</li>
<li>
<label>
<input type="radio"name="bd" class="bdmain-child" disabled="true"/>
Exceeding Four Years
</label>
</li>
</ul>
</body>
Assuming you can use jQuery:
$(function() {
// select by name to handle disabling the button if the radio is deselected
$("[name='educationalqualification']").click(function(e) {
// enable/disable child items if parent is not checked
$(".bdmain-child").prop("disabled", !$('#bdmain').is(':checked'));
});
});
JSFiddle Sample
You have radio buttons so I assume that there are multiple parent-children groups that need to behave properly. Fortunately you didn't tag jQuery so is a nice exercise not to forget javascript:
var parentChecks = document.getElementsByName('educationalqualification');
for (var i = 0; i < parentChecks.length; i++ ) {
parentChecks[i].addEventListener('change', function(e) {
for (var j = 0; j < parentChecks.length; j++) {
var radio = document.querySelectorAll('#' + parentChecks[j].dataset.group + ' input[type=radio]');
for (var k = 0; k < radio.length; k++) {
radio[k].disabled = !parentChecks[j].checked;
if (!parentChecks[j].checked) {
radio[k].checked = false;
}
}
}
}, false);
}
Demo: http://jsfiddle.net/Q9PZF/
In order to enable/disable child elements, the parent element must be enabled.
Try this code in which parent is enabled and on clicking it, its child radio elements will be enabled.
<html>
<head>
<script type='text/javascript'>
function enableChildren() {
var bdEls = document.getElementsByName('bd');
for(var i=0;i<bdEls .length;i++)
bdEls[i].disabled=false;
}
}
</script>
</head>
<body>
<p><input type="radio" name="educationalqualification" onClick="enableChildren()" id="bdmain"/>Bachelor's Degree</p>
<label><input type="radio" name="bd" disabled="true"/>Four Years</label></li>
<label><input type="radio" name="bd" disabled="true"/>Exceeding Four Years</label></li>
</body>
</html>

Categories