I need to toggle all buttons with a single function. Function needs to toggle all checkboxes in the document as my checkboxes are freestanding and not part of a form.
I currently have this, but it is not working properly. I get syntax error: syntax error in my firefox console.
checked=false;
function checkedAll() {
var c = new Array();
c = doc.getElementsByTagName('input');
if (checked == false){
checked = true;
}else{
checked = false;
}
for (var i = 0; i < c.length; i++){
if (c[i].type == 'checkbox'){
c[i].checked = checked;
}
}
}
How can I fix my code?
Thanks
Two main items to refactor. First, instead of doc it must be document. Second instead of relying on a global just pass in a boolean to determine whether or not to check the checkboxes.
function checkedAll(isChecked) {
var c = document.querySelectorAll('input[type="checkbox"]');
for (var i = 0; i < c.length; i++){
c[i].checked = isChecked;
}
}
JS Fiddle: http://jsfiddle.net/Jvnfm/107/
You can alternatively perform the following for each checkbox element:
c[i].click();
This version will trigger any associated event handlers associated with that element.
Related
I have a page with multiple radiofields from wtforms. I want to only allow the user to click the submit button if they have chosen an answer for all of the radiofields. I'm using flask for the framework. Here's my javascript:
<script>
function disableSubmit () {
console.log("function called")
var radios = document.querySelectorAll('[type="radio"]');
var all_questions_answered = true;
for (var i = 0; i < radios.length; i++) {
if (!(radios[i].checked)) {
all_questions_answered = false;
break;
}
}
const buttons = ["submit"];
if (!all_questions_answered) {
console.log("true");
buttons.forEach(element => document.getElementById(element).disabled = true);
} else {
console.log("false");
buttons.forEach(element => document.getElementById(element).disabled = false);
}
};
window.onload = function() {
console.log("windows onload");
disableSubmit();
};
</script>
The problem is that it always disables the submit button. This is because each radiofield has multiple radios, and the user can only select one radio per radiofield. I want to check if the user has answered each radiofield, whereas my code checks if all radios have been pressed. How can I check if the user has answered each radiofield?
I was able to solve this problem by counting the total number of radios, dividing it by the number of radios per radiofield, and checking if that is equal to the number of checked radios. If it is, the submit button is enabled.
Firstly you need to listen your radio buttons.
window.onload = function() {
for (var i = 0; i < document.querySelectorAll('[type="radio"]').length ; i++){
document.querySelectorAll('[type="radio"]')[i].addListener('onchange', 'checkSubmitButtons()');
}
};
After you can check all radio buttons are checked or not.
function checkSubmitButtons(){
var allRadioButtonsNotChecked = true;
for (var i = 0; i < document.querySelectorAll('[type="radio"]').length ; i++){
if (document.querySelectorAll('[type="radio"]')[i].checked){
allRadioButtonsNotChecked = false;
}else{
continue;
}
document.getElementById('myButton').disabled = allRadioButtonsNotChecked
}
Your button:
<button id="myButton" disabled>Submit</button>
The next possible problem is on Flask side. You may misunderstanding about of radio fields.
When we use radio checks?
If we want single choice in many options, we use radio fields.
Why i need this information?
If your radio fields have same name property, you can not check all of them one time.
This is an email preferences form with a bunch of checkboxes (16) to allow users to subscribe/unsubscribe.
I have a collection of checkboxes like this;
var checkboxes = document.querySelectorAll('input[type="checkbox"]');
I have a button which when clicked will select all checkboxes on the page and then deselect the unsubscribeAll checkbox;
getAllButton.addEventListener("click", function () {
selectAll();
});
function selectAll() {
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].type == "checkbox") checkboxes[i].checked = true;
}
// un-check the unsubscribeAll checkbox
unsubscribeAll.checked = false;
}
I have a checkbox which when clicked(checked) will deselect all of the other checkboxes on the page;
var unsubscribeAll = document.getElementById("unsubscribeAll");
unsubscribeAll.addEventListener("click", function () {
// un-check this box if already checked
if (this.checked !== true) {
this.checked = false;
} else {
deselectAll();
}
});
function deselectAll() {
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].type == "checkbox") checkboxes[i].checked = false;
}
unsubscribeAll.checked = true;
}
This is all working perfectly. However, my problem is that if the the unsubscribeAll checkbox is checked and the user then selects a checkbox to subscribe to an email I want to deselect the unsubscribeAll checkbox but I'm struggling to make that happen.
I thought I would be able to run another function that would deselect that checkbox like this;
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener("click", deselectUnsubscribeAll);
}
function deselectUnsubscribeAll() {
if (unsubscribeAll.checked === true) {
unsubscribeAll.checked = false;
}
}
Of course, this doesn't work because unsubscribeAll is included in the checkboxes[] array.
Next, I thought I would be able to create a new array of checkboxes that excluded unsubscribeAll so I tried this because it's the last element in that array;
var unsubscribeAll = document.getElementById("unsubscribeAll");
var getAllButton = document.getElementById("select-all");
var checkboxes = document.querySelectorAll('input[type="checkbox"]');
console.log(checkboxes.length); // 16
var popped = checkboxes.pop(); // Uncaught TypeError: checkboxes.pop is not a function
As you can see, that generates an error but I don't understand why. This seems like clunky code but it almost works.
This is one of the pages that I referenced to solve my problem;
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop#examples
I need some direction please.
You say it's the last element in that array, so why do you loop through the end of array and not using for (var i = 0; i < checkboxes.length - 1; i++)?
And then you can add an event listener separately to that.
You can also use Element.matches() API to check if the clicked checkbox is unsubscribeAll and run appropriate functions accordingly. But the first method is more efficient cause you don't need to check for the element on each click event.
Hi I am using Titanium to create a table of row that can be checked.
I need to write some code in Javascript that allows only one row to be checked and when one is checked the other ones are unchecked.
I am not worried about Titanium part but more about a general solution.
I know I need to setup an array of all the rows. What do I do next when one box is checked? How would I go through the other ones and tell them to become unchecked?
Thanks for your help.
Live example : http://jsfiddle.net/ztm82/
function doit(table, event) {
if (event.target.nodeName === "INPUT"
&& event.target.type === "checkbox"
&& event.target.checked)
{
var rows = table.tBodies[0].rows;
for (var i = 0; i < rows.length; i++)
{
var input = rows[i].getElementsByTagName("INPUT")[0];
if (input !== event.target)
{
input.checked = false;
}
}
}
}
Try something like this:
var checkboxes = document.querySelectorAll('#myTable input[type="checkbox"]'),
checkboxClickHandler,
i;
checkboxClickHandler = function (event) {
var i;
// only uncheck if target is a checkbox which has been checked
if (event.target.checked) {
for (i = 0; i < checkboxes.length; i++) {
// don't uncheck clicked box
if (checkboxes[i] !== event.target) {
checkboxes[i].checked = false;
}
}
}
};
document.getElementById('#myTable').addEventListener('click', checkboxClickHandler, false);
Mutually exclusive checkboxes? Why not use radio buttons (<input type='radio'>) instead? You'd get this behaviour for free and it would be more intuitive for users.
I wanna check radio buttons automatically: I tried this code but it does not work:
Radio buttons have 3 different values, I wanna select the radio button with value 'clean".
How can I check automatically radio buttons on a webpage?
Thanks!
function getElements()
{
for (i=0; i<document.getElementsByTagName('input').length; i++)
{
//if (document.getElementsByTagName('input')[i].type == 'radio')
if(document.getElementsByTagName('input')[i].type=='radio')
{
//if (document.getElementsByTagName('input')[i].value=='clean')
document.getElementsByTagName('input')[i].click();
}
}
I modified the code as following:
for (i=0; i<document.getElementsByTagName('input').length; i++)
{
if(document.getElementsByTagName('input')[i].type=='radio')
{
if(document.getElementsByTagName('input')[i].value == "clean")
{
document.getElementsByTagName('input')[i].checked =true;
}
}
}
but it is not still working:(
the radio buttons are in a iframe, can it be the reason why the code is not working?
Give your radio buttons "names" would make things a lot easier
<input type="radio" name="myradios" value="clean"/>
<input type="radio" name="myradios" value="somethingelse"/>
var elements = document.getElementsByName('myradios');
for (i=0;i<elements.length;i++) {
if(elements[i].value == "clean") {
elements[i].checked = true;
}
}
Working example : http://jsfiddle.net/Dwzc9/
Updated
getElementsByName doesn't seem to be supported in all IE versions ... so you could use the following based on your original example :
var allElems = document.getElementsByTagName('input');
for (i = 0; i < allElems.length; i++) {
if (allElems[i].type == 'radio' && allElems[i].value == 'clean') {
allElems[i].checked = true;
}
}
Working example : http://jsfiddle.net/Dwzc9/2/
you might try setting the "checked" attribute instead.
var getElements = function()
{
var x = document.getElementsByTagName("input");
var oldname = '';
for(var i = 0; i < x.length; i++)
{
if(x[i].type == 'radio' && x[i].name != oldname && x[i].value == 'clean')
{
x[i].checked = true;
oldname = x[i].name;
}
}
};
The problem with this function is that it will attempt to check all the radio buttons, so if they belong to a group (which is usually the case), only the last radio button from each group will be selected. If that is your intention, then great, otherwise it bears thinking about how to decide which button is selected, and breaking the loop. You can see in the function above that I have decided to select only the first button in the group, by checking the name attribute of the element.
I hope this helps you!
Matt
UPDATE
Another way to handle this, using jQuery, would be:
var getElements = function(){
var oldname = '';
$.each($('input[type="radio"]'), function(){
if($(this).attr('name') != oldname && $(this).val() == 'clean'){
$(this).checked = true;
oldname = this.name;
}
});
};
I'm running into some type of error here. Nothing is happening. Does anyone have idea idea why?
Thank you beforehand!
-form_tag :action => 'form', :name =>'admin_form' do
#images_actions_bar
.select_all
=check_box_tag('check_all', 'check_all', false, :onClick => "$$('admin_form input.check').each(function(box){box.checked=true});return false;")
==============
thanks. what ultimately worked for me was a check box like this:
=check_box_tag('check_all', 'check_all', false, :onClick => "checkAll(document.admin_form.check_all, document.admin_form.checkbox);")
and a js function like this:
function checkAll(field_main, fields){
if(field_main.checked == true){
for (i = 0; i < fields.length; i++)
fields[i].checked = true ;
}else{
for (i = 0; i < fields.length; i++)
fields[i].checked = false;
}
It's not clear what javascript framework you're using. I've really only used jQuery and (minimally) Prototype. So, I'd check that admin_form is selecting the form element properly. In jQuery, it would have to be form[name="admin_form"]
I've modified a check/uncheck all jquery piece that I previously wrote. Hopefully it may help. First, clicking "check_all" will check all checkboxes. Clicking a checkbox will then uncheck the "check_all" checkbox.
$('#check_all').click(function() {
var checkboxes = $('form[name="admin_form"] > input:checkbox');
$(checkboxes).each(
function(){
this.checked = $('#check_all').attr('checked');
}
);
});
$('form[name="admin_form"] > input:checkbox').click(function() {
var checkAll = $('#check_all');
if ($(checkAll).is(':checked') && !($(this).is(':checked')))
{ $(checkAll).removeAttr('checked'); }
});
The answer posted in the original question got me started but I ran into problems because my checkboxes are named message_id[]. The brackets were causing JS syntax errors.
Following a pattern in this thread, I got around this by looping through all the input fields on the form and then operating explicitly on the ones with type="checkbox".
This code in my view creates the Check All checkbox (intentionally without a label):
<%= check_box_tag('check_all', 'check_all', false, :onClick => "checkAll(this);") %>
which uses this JavaScript:
function checkAll(check_all){
// Pass in a named "Check All" checkbox that appears on the same form where all
// checkboxes should be checked.
// Loop through an array containing ALL inputs on same form as check_all
var inputs = check_all.form.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
// Only work on checkboxes, and NOT on the "Check All" checkbox
if (inputs[i].type == "checkbox" && inputs[i].name != check_all.name) {
if(check_all.checked == true){
inputs[i].checked = true ;
}else{
inputs[i].checked = false ;
}
}
}
}
function checkAll(check_all){
// Pass in a named "Check All" checkbox that appears on the same form where all
// checkboxes should be checked.
// Loop through an array containing ALL inputs on same form as check_all
var inputs = check_all.form.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
// Only work on checkboxes, and NOT on the "Check All" checkbox
if (inputs[i].type == "checkbox" && inputs[i].name != check_all.name) {
inputs[i].checked = check_all.checked ;
}
}
}