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

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

Related

uncheck checked radio button

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>

Getting error [object HTMLCollection]

I am having a problem in making a simple test in javascript. This is a quick example. Each question's div id is incremented in the html code.
HTML
<form action="#">
<div id="q1">
<label>Q. ABCD</label>
<label><input type="radio" name="radio1" value="1">A</label>
<label><input type="radio" name="radio1" value="2">B</label>
<label><input type="radio" name="radio1" value="3">C</label>
<label><input type="radio" name="radio1" value="4">D</label>
</div>
....
....
<input type="button" value="Click to Submit" onClick="result();">
</form>
JS (say for 10 questions)
function result() {
var answer = new Array();
for(var i=1; i<11 ; i++) {
if(document.getElementById("q" + i).getElementsByTagName("input") != undefined) {
answer[i] = document.getElementById("q" + i).getElementsByTagName("input");
}
else {
answer[i] = 0;
}
}
console.log(answer);
}
I am getting an error [object HTMLCollection] every time I submit the code. How should I do this so that I can get the value of each answer given inside the array and if someone doesn't answer any question, the array must get 0 value at its place instead of undefined. I need a pure JS and HTML solution.
Try this one
function result() {
var answer = new Array();
// there is no answer 0
answer[0] = 'unused';
for(var i=1; i<11 ; i++) {
// check if the id exists first
var container = document.getElementById("q" + i);
if(container) {
// get the selected radio checkbox
var input = container.querySelector("input:checked");
// if there's one selected, save it's value
if(input) {
answer[i] = input.value;
}
else {
answer[i] = 0;
}
}
}
console.log(answer);
}
a working fiddle - http://jsfiddle.net/dtpLjru1/
In your code, you are trying to store the HTML collection by using getElementByTagName(). This method will return all the Tags with the name of "input", so total of 4 tags as per the code above.
Instead of that, you can modify your code like below.
Assuming, you want to store "1" in case radio button is checked. else 0
function result() {
var answer = new Array();
for (var i = 1; i <= 4 ; i++) {
if (document.getElementById("q" + i).getElementsByTagName("input") != undefined) {
answer[i] = document.getElementById("q" + i).checked ? 1 : 0;
}
else {
answer[i] = 0;
}
}
console.log(answer);
}
Have not tested the code, How about we do this ?
function result() {
var answer = new Array();
for(i=1; i<11 ; i++) {
if(document.getElementById("q" + i).getElementsByTagName("input") != undefined) {
document.write( document.getElementById("q" + i).getElementsByTagName("input") );
}
else {
document.write(0);
}
}
}

Trouble setting and adding array values javascript

I want to give each check box an integer value and then if the box is checked add the values and display the total in a text box with the ID="options". So far the code is not sending a value to the desired location. Any instruction on how to improve the code would be helpful. Thank you.
<html>
<body>
<form id="registration" name="registration">
<input name="opt1" value="5" type="checkbox"> Breakfast ($5)
<input name="opt2" value="10" type="checkbox"> Lunch ($10)
<input name="opt3" checked="checked" value="0" type="checkbox"> Happy Hour (free!)
<input id="options" name="options" type="text">
</form>
</body>
</html>
<script>
function getOptions() {
var form = document.getElementById("registration"),
inputs = form.getElementsByTagName("input"),
result = 0;
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type === "checkbox" && inputs[i].checked) {
result += inputs[i].value;
document.getElementById("options").value = result;
}
}
}
getOptions();
</script>
You may need to attach onchange event handlers to the checkboxes as shown below. And you should parse inputs[i].value to a number using parseFloat() before adding it to result.
var form = document.getElementById("registration"),
inputs = form.getElementsByTagName("input");
function getOptions() {
var result = 0;
for (var i = 0, len = inputs.length; i < len; i++) {
if (inputs[i].type === "checkbox" && inputs[i].checked) {
result += parseFloat(inputs[i].value);
}
}
document.getElementById("options").value = result;
}
for (var i = 0, len = inputs.length; i < len; i++) {
if (inputs[i].type === "checkbox") {
inputs[i].onchange = function () {
getOptions();
}
}
}
getOptions();
JSFiddle

I have an issue to create dynamic fields with string count using Javascript OR Jquery

I have an issue to create dynamic fields with string count using JavaScript or jQuery.
Briefing
I want to create dynamic fields with the help of sting count, for example when I write some text on player textfield like this p1,p2,p3 they create three file fields on dynamicDiv or when I remove some text on player textfield like this p1,p2 in same time they create only two file fields that's all.
The whole scenario depend on keyup event
Code:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function commasperatedCount(){
var cs_count = $('#player').val();
var fields = cs_count.split(/,/);
var fieldsCount = fields.length;
for(var i=1;i<=fieldsCount;i++){
var element = document.createElement("input");
element.setAttribute("type", 'file');
element.setAttribute("value", '');
element.setAttribute("name", 'file_'+i);
var foo = document.getElementById("dynamicDiv");
foo.appendChild(element);
}
}
</script>
<form>
<label>CountPlayerData</label>
<input type="text" name="player" id="player" onkeyup="return commasperatedCount();" autocomplete="off" />
<div id="dynamicDiv"></div>
<input type="submit" />
</form>
var seed = false,
c = 0,
deleted = false;
$('#player').on('keyup', function(e) {
var val = this.value;
if ($.trim(this.value)) {
if (e.which == 188) {
seed = false;
}
if (e.which == 8 || e.which == 46) {
var commaCount = val.split(/,/g).length - 1;
if (commaCount < c - 1) {
deleted = true;
}
}
commasperatedCount();
} else {
c = 0;
deleted = false;
seed = false;
$('#dynamicDiv').empty();
}
});
function commasperatedCount() {
if (deleted) {
$('#dynamicDiv input:last').remove();
deleted = false;
c--;
return false;
}
if (!seed) {
c++;
var fields = '<input value="" type="file" name="file_' + c + '">';
$('#dynamicDiv').append(fields);
seed = true;
}
}​
DEMO
<script>
function create(playerList) {
try {
var player = playerList.split(/,/);
} catch(err) {
//
return false;
}
var str = "";
for(var i=0; i<player.length; i++) {
str += '<input type="file" id="player-' + i + '" name="players[]" />';
//you wont need id unless you are thinking of javascript validations here
}
if(playerList=="") {str="";} // just in case text field is empty ...
document.getElementById("dynamicDiv").innerHTML = str;
}
</script>
<input id="playerList" onKeyUp="create(this.value);" /><!-- change event can also be used here -->
<form>
<div id="dynamicDiv"></div>
</form>

Javascript Toggle Check All Nested Array Names

I'm having a problem trying to create a Javascript function that checks all the checkboxes in a form.
An example of the checkboxes on my form look like
<b>A:</b> <input type="checkbox" name="multipleForms[201][A]"><br>
<b>B:</b> <input type="checkbox" name="multipleForms[201][B]"><br>
<b>C:</b> <input type="checkbox" name="multipleForms[201][C]"><br>
<b>D:</b> <input type="checkbox" name="multipleForms[201][D]"><br>
<b>A:</b> <input type="checkbox" name="multipleForms[500][A]"><br>
<b>B:</b> <input type="checkbox" name="multipleForms[500][B]"><br>
<b>C:</b> <input type="checkbox" name="multipleForms[500][C]"><br>
And what I want to do is be able to pass a number such as 201 and 500 into a Javascript function and have all checkboxes with the first array index as that integer be checked.
So, checkAll(201) would have the first 4 checkboxes checked and checkAll(500) would have the other 3 checkboxes checked.
I would rather not change the names of my checkboxes if that is possible as the stringed indexes are really important for my PHP code.
Thanks in advance.
Also, I would rather have non-jQuery code.
Something like that ? : http://jsfiddle.net/RZPNG/6/
var checkboxes = document.getElementsByTagName('input');
function check(num) {
for (var i = 0; i < checkboxes.length; i++) {
if (parseInt(checkboxes[i].name.split('[')[1]) === num) {
checkboxes[i].checked = 'checked';
}
}
}
check(201);​
Something like the following should do:
function checkBoxes(form, s) {
var input, inputs = form.getElementsByTagName('input');
var re = new RegExp(s);
for (var i=0, iLen=inputs.length; i<iLen; i++) {
input = inputs[i];
if (input.type == 'checkbox' && re.test(input.name)) {
input.checked = true;
} else {
input.checked = false;
}
}
}
You could also use querySelectorAll, but support isn't that common yet:
function checkBoxes(s) {
var els = document.querySelectorAll('input[name*="' + s + '"]');
for (var i=0, iLen=els.length; i<iLen; i++) {
els[i].checked = true;
}
}

Categories

Resources