uncheck checked radio button - javascript

var radios = document.getElementsByTagName('input');
for (i = 0; i < radios.length; i++) {
radios[i].onclick = function () {
if (this.checked) {
this.checked = false;
}
}
}
<div id = "container">
<input type = "radio" name = "x"> A
<br>
<input type = "radio" name = "x"> B
</div>
what i want is to check one of the radios and if i pressed the checked radio again to uncheck it but it does not check in first place too
how to uncheck a checked radio after it was checked and how to even tell that it is checked or in empty state

I will suggest that you use attribute to control the checked status.
var x = document.getElementsByName('x');
x.forEach(function(e) {
e.addEventListener('click', function(ev) {
// set checked by data-checked attribute
if (e.getAttribute('data-checked') == 'true') {
e.checked = false;
e.setAttribute('data-checked', 'false');
} else {
e.checked = true;
e.setAttribute('data-checked', 'true');
}
// update attribute of all radios
x.forEach(function(e2) {
e2.setAttribute('data-checked', e2.checked);
});
});
});
<input type="radio" name="x" data-checked="false"> A<br>
<input type="radio" name="x" data-checked="false"> B<br>
<input type="radio" name="x" data-checked="false"> C<br>

Using your current JavaScript code, the moment you click it, it will be checked first before reading the JavaScript code, thus it will appear to be unchecked always. With my suggestions (it can't be helped sorry) use something like this:
var radios = document.getElementsByTagName('input');
for (i = 0; i < radios.length; i++) {
radios[i].onmousedown = function () {
if (this.checked) {
this.checked = false;
this.onchange = function () {
this.checked = false;
}
}
else {
this.checked = true;
this.onchange = function () {
this.checked = true;
}
}
}
}
<div id = "container">
<input type = "radio" name = "x"> A
<br>
<input type = "radio" name = "x"> B
</div>
Since I can't question you why you can't use checkbox instead, I had to do this. It works for me anyway

Use the following code. This is the whole code, try using it:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body >
<div id = "container">
<input type = "radio" name = "x"> A
<br>
<input type = "radio" name = "x"> B
</div>
</body>
<script type="text/javascript">
var radios = document.getElementsByTagName('input');
for (i = 0; i < radios.length; i++) {
radios[i].onclick = function () {
console.log("==>" , this.checked);
if (this.checked == false) {
this.checked = true;
}else{
this.checked = true;
}
}
}
</script>
</html>

Related

Maintain visibility of a form-textinput when checkbox is checked

In my HTML I have a form, where a user can select the checkbox "other" and a textbox appears. Otherwise the textbox is hidden. Below you can find my code. But if the user selects "other", types in his text und submits the form, the textbox is hidden again-although the checkbox maintain checked (saved in localStorage). I cannot find my mistake here.
Form:
<label class="form-check">
<input class="form-check-input" name="filetype" type="checkbox" id="other" value="" onclick="save()">
<span class="form-check-label"
<input placeholder="e.g. 'msg'" name="other" onsubmit="save();" class="form-control input-lg" type="text" id="otherValue" value="{{extension}}">
</span>
</label> <!-- form-check -->
Visible/Hidden
<!--"Other"-filter-->
<script type="text/javascript">
var otherCheckbox = document.querySelector('input[id="other"]');
var otherText = document.querySelector('input[id="otherValue"]');
otherText.style.visibility = 'hidden';
otherCheckbox.onchange = function(){
if(otherCheckbox.checked) {
otherText.style.visibility = 'visible';
otherCheckbox.value = otherText.value;
save();
} else {
otherText.style.visibility = 'hidden';
}
};
</script>
Tried to solve this Problem by saving the info in the sessionStorage but it still does not work.
<!--Save Checkbox-State-->
<script type="text/javascript">
const checkboxen = [...document.querySelectorAll("[type=checkbox]")].map(inp => inp.id); //list of all checkbox-IDs
function save(){
for (var i = 0 ; i< checkboxen.length; i++){
var id = checkboxen[i];
var checkbox = document.getElementById(id);
sessionStorage.setItem(id,checkbox.checked);
}
var other = document.getElementById('otherValue');
sessionStorage.setItem('otherValue',other.style.visibility);
}
function load(){
for (var i = 0 ; i< checkboxen.length; i++){
var id = checkboxen[i];
var checked =JSON.parse(sessionStorage.getItem(id));
document.getElementById(id).checked = checked;
}
var other = JSON.parse(sessionStorage.getItem('otherValue'));
document.getElementById('otherValue').style.visibility = other;
}
function deleteCheckbox(){
sessionStorage.clear();
}
</script>
Thanks for any help <3
with prop jquery:
<script>
$(function(){
var other = localStorage.input === 'true'? true: false;
$('input').prop('checked', other);
});
$('input').on('change', function() {
localStorage.input = $(this).is(':checked');
console.log($(this).is(':checked'));
});
</script>
this is my solution:
<script type="text/javascript">
var other = document.getElementById('other');
var otherText =document.querySelector('input[id="otherValue"]');
$(document).ready(function(){
if (other.checked){
otherText.style.visibility = 'visible';
otherText.value = "{{extension}}";
other.value = "{{extension}}";
} else {
otherText.style.visibility = 'hidden';
otherText.value = "";
}
});

Programatically checking all checkbox doesn't work properly when any of the target checkboxes checked / unchecked manually

Programatically checking all checkbox doesn't work properly when any of the target checkboxes checked / unchecked manually
I have two methods, where one will check all the checkboxes and other will un check all the checkbox values
I named them selectAll and unSelectall. when selectAll is triggered, it will check all the checkbox but when unSelectall is triggered it unchecks all the checkbox but what the problem is when you check / uncheck the any of the target checkboxes and then you click the checkall or uncheck all, the manually checked/ unchecked checkboxes don't work. here is the working code on fiddle
function selectAll() {
const checkboxes = document.querySelectorAll('.myCheck');
let i = 0;
while(i < checkboxes.length) {
checkboxes[i].setAttribute("checked", "checked");
i++;
}
}
function unSelectAll() {
const checkboxes = document.querySelectorAll('.myCheck');
let i = 0;
while(i < checkboxes.length) {
checkboxes[i].removeAttribute("checked", "");
i++;
}
}
Instead of setAttribute and removeAttribute, use the direct checked property
function selectAll() {
const checkboxes = document.querySelectorAll('.myCheck');
let i = 0;
while (i < checkboxes.length) {
checkboxes[i].checked = true;
i++;
}
}
function unSelectAll() {
const checkboxes = document.querySelectorAll('.myCheck');
let i = 0;
while (i < checkboxes.length) {
checkboxes[i].checked = false;
i++;
}
}
Demo
<!DOCTYPE html>
<html>
<body>
All:
<input onclick="selectAll();" type="checkbox" id="all"> uncheckAll:
<input onclick="unSelectAll();" type="checkbox" id="all">
<br/> ckbx1:
<input type="checkbox" class="myCheck"> ckbx2:
<input type="checkbox" class="myCheck"> ckbx3:
<input type="checkbox" class="myCheck"> ckbx4:
<input type="checkbox" class="myCheck">
<p>checl all and uncheck all</p>
<script>
function selectAll() {
const checkboxes = document.querySelectorAll('.myCheck');
let i = 0;
while (i < checkboxes.length) {
checkboxes[i].checked = true;
i++;
}
}
function unSelectAll() {
const checkboxes = document.querySelectorAll('.myCheck');
let i = 0;
while (i < checkboxes.length) {
checkboxes[i].checked = false;
i++;
}
}
</script>
</body>
</html>

Button enabled from 3 condition

I'm trying to get the button to be enabled only when all three condition are met which are at least one checkbox is selected in the 1st checkbox list and 2nd checkbox selected and option list selected.
For the 1st condition i was thinking as an alternative would javascript be able to check on strlen of the textbox ?
Somehow the pure javascript below is not working and would it be possible if selection by the user goes in reverse ?
Pure javascript:
<script type = "text/javascript">
document.addEventListener("DOMContentLoaded", function() {
document.getElementById('termsChkbx').addEventListener("change", function(){
this.parentNode.style.color = this.checked ? "black" : "red";
}, false);
});
function change(obj) {
var selectBox = obj;
var selected = selectBox.options[selectBox.selectedIndex].value;
var retCustDetails = document.getElementById("retCustDetails");
var tradeCustDetails = document.getElementById("tradeCustDetails");
if(selected === 'ret'){
retCustDetails.style.display = "block";
tradeCustDetails.style.display = "none";
}
else if (selected === 'trd') {
retCustDetails.style.display = "none";
tradeCustDetails.style.display = "block";
}
else if (selected === '') {
retCustDetails.style.display = "none";
tradeCustDetails.style.display = "none";
}
}
function isChecked() {
var sum = 0; //store a running sum
//find all price elements: class "CDPrice" within element of class "item"
[].forEach.call(document.querySelectorAll(".item .CDPrice"), function(item) {
//get the corresponding checkbox
var chosen = item.parentElement.querySelector('[type="checkbox"]');
//if checked, add to the running sum
if (chosen.checked) {
var value = parseFloat(item.innerHTML) || 0; //if parseFloat() returns none, default value to zero
sum += value;
}
});
//update the total
var total = document.getElementById("total");
total.value = sum.toFixed(2);
}
function Checked() {
var checkedRadioButtons = document.querySelector('[name="deliveryType"]:checked');
document.getElementById("total").value = checkedRadioButtons.getAttribute("title");
}
//conditions for submit button to be enable
//var firstCondition = document.querySelectorAll('name=CDPrice');
//var termsCheckbox = document.getElementById('termsChkbx');
var show = document.getElementById('show');
var button = document.getElementById('sub1');
var conditions = {
// cond1: false,
// cond2: false,
cond3: false
};
//function setCondition1(e) {
// conditions.cond1 = e.target.checked;
// enableButton(conditions);
//}
//function setCondition2(e) {
// conditions.cond2 = e.target.checked;
// enableButton(conditions);
//}
function setCondition3(e) {
conditions.cond3 = e.target.value && e.target.value.length > 0;
enableButton(conditions);
}
function enableButton(options) {
if (options.cond3) {
button.removeAttribute('disabled');
} else {
button.setAttribute('disabled', true);
}
}
//for(i=0 ; i< firstCondition.length ; i++){
// firstCondition[i].addEventListener("click", setCondition1, false);
//}
//termsCheckbox.addEventListener('change', setCondition2, false);
show.addEventListener('change', setCondition3, false);
</script>
1st condition -> Checkbox list or textbox:
<?php
include_once('database_conn.php');
$sqlCDs = 'SELECT CDID, CDTitle, CDYear, catDesc, CDPrice FROM nmc_cd b inner join nmc_category c on b.catID = c.catID WHERE 1 order by CDTitle';
$rsCDs = mysqli_query($conn, $sqlCDs);
while ($CD = mysqli_fetch_assoc($rsCDs)) {
echo "\t<div class='item'>
<span class='CDTitle'>{$CD['CDTitle']}</span>
<span class='CDYear'>{$CD['CDYear']}</span>
<span class='catDesc'>{$CD['catDesc']}</span>
<span class='CDPrice'>{$CD['CDPrice']}</span>
<span class='chosen'><input type='checkbox' name='CD[]' value='{$CD['CDID']}' title='{$CD['CDPrice']}'onchange='isChecked();'/></span>
</div>\n";
}
?>
<section id="checkCost">
<h2>Total cost</h2>
Total <input type="text" name="total" id="total" size="10" readonly="readonly" />
</section>
2nd condition -> 2nd checkbox:
<p style="color: red; font-weight: bold;">I have read and agree to the terms and conditions
<input type="checkbox" id="termsChkbx" onchange="isChecked(this,'sub1')"/></p>
3rd condition -> Option List:
<section id="placeOrder">
<h2>Place order</h2>
Your details
Customer Type: <select id="show" name="customerType" onchange="change(this)">
<option value="">Customer Type?</option>
<option value="ret">Customer</option>
<option value="trd">Trade</option>
</select>
Submit Button:
<p><input type="submit" name="submit" value="Order now!" id="sub1" disabled="disabled"/></p>
You can attach event listeners on each input and listen for changes.
var firstCondition = document.querySelectorAll('input[name="testName"]');
var termsCheckbox = document.getElementById('termsChkbx');
var show = document.getElementById('show');
var button = document.getElementById('sub1');
Object to hold all the conditions
var conditions = {
cond1: false,
cond2: false,
cond3: false
}
Declared functions to use with addEventListener
function setCondition1(e) {
conditions.cond1 = e.target.checked;
enableButton(conditions);
}
function setCondition2(e) {
conditions.cond2 = e.target.checked;
enableButton(conditions);
}
function setCondition3(e) {
conditions.cond3 = e.target.value && e.target.value.length > 0;
enableButton(conditions);
}
Enable button
function enableButton(options) {
if (options.cond1 && options.cond2 && options.cond3) {
button.removeAttribute('disabled');
} else {
button.setAttribute('disabled', true);
}
}
Add event listeners
for(i=0 ; i< firstCondition.length ; i++){
firstCondition[i].addEventListener("click", setCondition1, false);
}
termsCheckbox.addEventListener('change', setCondition2, false);
show.addEventListener('change', setCondition3, false);
example: http://jsfiddle.net/qjo9rqgc/

Form redirect on checkbox selection

Here's what i'm trying to achieve: I want to create a HTML page with a form, when you submit the form it goes to 1 of 4 locations. There is a default hidden main option thats auto-selected on page load and 2 sub-options that are optional.
Oh, and it calculates the amounts on selection!
Here's my code so far:
<html>
<head></head>
<body>
<form onSubmit="submitForm();" id="myForm" type="get">
<input id="myCheckbox1" name="myCheckbox1" type="checkbox" value="20" onClick="calcNow();" />Default option<br/>
<input id="myCheckbox2" name="myCheckbox2" type="checkbox" value="30" onClick="calcNow();" />Add-on option 1<br/>
<input id="myCheckbox2" name="myCheckbox2" type="checkbox" value="40" onClick="calcNow();" />Add-on option 2<br/>
<input id="myTotal" name="myTotal" type="text" value="" disabled="disabled" /><br/>
<input type="button" id="myButton" onClick="submitForm();" value="Continue" />
</form>
<script type="text/javascript">
var pages = [[["http://mysite.com/page1.html"],["http://mysite.com/page2.html"],["http://mysite.com/page3.html","http://mysite.com/page4.html"]]];
function calcNow()
{
var cb = document.getElementById("myCheckbox1");
var cb = document.getElementById("myCheckbox2");
var cost1 = cb.checked ? parseInt(cb.value) : 0;
var cost2 = cb.checked ? parseInt(cb.value) : 0;
var costTotal = cost1 + cost2;
document.getElementById("myTotal").value = costTotal;
var op1 = cb.checked ? 1 : 0;
if (op1 != undefined)
{
return pages[op1];
}
return undefined;
}
function submitForm()
{
var page = calcNow();
if (page != undefined)
{
alert(page);
// ---- To navigate ----
//location.href = page;
// ---- To alter post ----
//var form = document.getElementById("myForm");
//form.action = page;
//form.submit();
}
else
{
alert("Please answer all questions.");
}
}
function getRadioValue(name)
{
var controls = document.getElementsByName(name);
for (var i = 0; i < controls.length; i++) {
if (controls[i].checked) {
return parseInt(controls[i].value);
}
}
return 0;
}
function getRadioData(name, attribute)
{
var controls = document.getElementsByName(name);
for (var i = 0; i < controls.length; i++) {
if (controls[i].checked) {
return parseInt(controls[i].dataset[attribute]);
}
}
return undefined;
}
</script>
</body>
</html>
Try this
EDIT:
function submitForm()
{
//The code goes inside here, you have to decide where to redirect from if or the else
window.location.assign("http://www.w3schools.com/");
var page = calcNow();
if (page != undefined)
{
alert(page);
}
else
{
alert("Please answer all questions.");
}
}

Fast way to validate if all checkboxes are un-selected?

Is there a quick way or function that would tell me true/false if all check boxes are deselected? Without going through array? (with JS and HTML)
All my check boxes have the same name...
<form action="/cgi-bin/Lib.exe" method=POST name="checks" ID="Form2">
<input type=checkbox name="us" value="Joe" ID="Checkbox1">
<input type=checkbox name="us" value="Dan" ID="Checkbox2">
<input type=checkbox name="us" value="Sal" ID="Checkbox3">
</form>
jQuery would be a mass of unneeded bloat for a task this trivial. Consider using it if you are running it for other purposes, but all you need is something like this:
function AreAnyCheckboxesChecked () {
var checkboxes = document.forms.Form2.elements.us;
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
return true;
}
}
return false;
}
You have to loop through them. Even a library like jQuery will loop through them, just hide it from you.
var form = document.getElementById('Form2');
var inputs = form.getElementsByTagName('input');
var is_checked = false;
for(var x = 0; x < inputs.length; x++) {
if(inputs[x].type == 'checkbox' && inputs[x].name == 'us') {
is_checked = inputs[x].checked;
if(is_checked) break;
}
}
// is_checked will be boolean 'true' if any are checked at this point.
JavaScript:
var allischecked = (function(){
var o = document.getElementById("Form2").getElementsByTagName("input");
for(var i=0,l=o.length;i<l;i++){
o[i].type === "checkbox" && o[i].name === "us" && o[i].checked || return false;
}
return true;
})();
With jQuery:
var allischecked = ($("#Form2 input:checkbox:not(checked)").length === 0);
In summary, this snipped will return true if all are NOT checked. It bails out as soon as a checked one is found.
var a = document.getElementsByName("us");
for(var i=0; i<a.length; i++)
if(a[i].checked)
return false;
return true;
(did not test, but conceptually it is valid)
What do you mean by
Without going through array
?
You could just do
function check() {
var anyChecked = false;
var form = document.getElementById('Form2');
var checkboxes = form.getElementsByTagName('input');
for(var i=0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
anyChecked = true;
break;
}
}
alert("Checkboxes checked? " + anyChecked);
}
Working Demo
If you have a large amount of checkboxes that you don't want to loop through to test it might be more efficient to use this approach.
var checked = 0;
$("input[type=checkbox]").live("click", function() {
if($(this).attr("checked")) checked++;
else checked--;
}
Then you would be able to test like this.
if(checked === 0) {
doSomething();
}
The proper solution with jQuery attribute checked:
$checkboxes = $('#Form2 input:checkbox');
$checkboxes.on('click', checkboxes);
function checkboxes() {
var allChecked = $checkboxes.not(':checked').length == 0;
console.log(allChecked);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<form action="/cgi-bin/Lib.exe" method=POST name="checks" ID="Form2">
<input type=checkbox name="us1" value="Joe" ID="Checkbox1"><label>Joe</>
<input type=checkbox name="us2" value="Dan" ID="Checkbox2"><label>Dan</>
<input type=checkbox name="us3" value="Sal" ID="Checkbox3"><label>Sal</>
</form>
Even easier without loop
const toggleCheckboxes = checkbox => {
if(checkbox.checked){
return true
}else{
if(document.querySelectorAll(':checked').length === 0){
// All are unchecked
return false
}
}
}

Categories

Resources