You need to select at least one radio button / checkbox - javascript

What would be the JavaScript code to check if the user has selected at least one radio button, knowing that the radio buttons all have the same "name" attribute?
Same question for checkboxes.
I do not use any fancy javascript frameworks such as JQuery and others ...

function IsARadioButtonChecked ( radiogroup ) {
for (var i = 0; i < radiogroup.length; i++) {
if (radiogroup[i].checked) {
return true;
}
}
return false;
}
if (IsARadioButtonChecked(document.forms.myForm.elements.myRadioGroupName)) {
// …
}

Related

How can I use javascript to check if each Wtform RadioField has a value?

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.

How can I remove the last checkbox from an array using vanilla javascript

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.

Disable submit button until one in a group of dynamically-created radio buttons selected

I would like to disable a submit button until one of a group of radio buttons is selected. I know there are similar questions out there, but none pertain to a dynamically-created group of radio buttons...
Here is what I have.. a script at the top of the page generates a number of buttons given a user upload in a previous view:
var jScriptArray = new Array(#ViewBag.ColNames.Length);
var array = #Html.Raw(Json.Encode(ViewBag.ColNames));
for( var i = 0; i < #ViewBag.ColNames.Length; i++ ) {
jScriptArray[i] = array[i];
}
var length = #(ViewBag.NCols);
$(document).ready(function () {
for (var i = 0; i < length; i++) {
$('#radioGroupBy').append('<input id="grp' + i +'" type="radio" name="group" value="'+i+'">'+jScriptArray[i]+'</input>')
$('#radioGroupBy').append('<p style="padding:0px;margin:0px;"></br></p>');
}
});
This works, and selecting any of the buttons returns the proper value; great. However, I want to disable the submit button until one of these radio buttons is selected. Using an answer I found on SO earlier, I created the following (this works, but only if I hard code the group of buttons. The issue is it won't work with the Javascript-created group):
var $radioButtons = $("input[name='group']");
$radioButtons.change(function () {
var anyRadioButtonHasValue = false;
// iterate through all radio buttons
$radioButtons.each(function () {
if (this.checked) {
// indicate we found a radio button which has a value
anyRadioButtonHasValue = true;
// break out of each loop
return false;
}
});
// check if we found any radio button which has a value
if (anyRadioButtonHasValue) {
// enable submit button.
$("input[name='submitbtn']").removeAttr("disabled");
}
});
Also, for the sake of thoroughness, here is the submit button:
<input id="submitbtn" name="submitbtn" type="submit" value="Drill Down" disabled="disabled" />
Thanks so much!
Event delegation (also, use .prop() when removing the disabled property to the submit button)
$("#radioGroupBy").on("change", ":radio[name=group]", function() {
var $radioButtons = $(":radio[name=group]");
var anyRadioButtonHasValue = false;
// iterate through all radio buttons
$radioButtons.each(function () {
if (this.checked) {
// indicate we found a radio button which has a value
anyRadioButtonHasValue = true;
// break out of each loop
return false;
}
});
// check if we found any radio button which has a value
if (anyRadioButtonHasValue) {
$("input[name='submitbtn']").prop("disabled", false);
}
});
I figured it out. As Benjamin suggested in comments above, the latter script was executing before the DOM was ready. I solved it by just surrounding the whole script in $(window).load... :
$(window).load(function () {
var $radioButtons = $("input[name='group']");
$radioButtons.change(function () {
var anyRadioButtonHasValue = false;
// iterate through all radio buttons
$radioButtons.each(function () {
if (this.checked) {
// indicate we found a radio button which has a value
anyRadioButtonHasValue = true;
// break out of each loop
return false;
}
});
// check if we found any radio button which has a value
if (anyRadioButtonHasValue) {
// enable submit button.
$("input[name='submitbtn']").removeAttr("disabled");
}
});
});

Checkmark to exclusive item in Javascript

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.

How to loop through a radio buttons group without a form?

How do I loop through a radio buttons group without a form in JavaScript or jQuery?
What about something like this? (using jQuery):
$('input:radio').each(function() {
if($(this).is(':checked')) {
// You have a checked radio button here...
}
else {
// Or an unchecked one here...
}
});
You can also loop through all the checked radio buttons like this, if you prefer:
$('input:radio:checked').each(function() {
// Iterate through all checked radio buttons
});
...in case someone wants to do this without jQuery (since it was part of the question):
I'm not sure what you mean by without a form. If you mean you don't want to pass the form element to a javascript function, you could do it like this:
for (var i = 0; i < document.form_name.radio_name.length; i++) {
if (document.form_name.radio_name[i].checked) {
// ...
}
}
If you mean without a form as in you have no form node, you could wrap them in a span (or a div) and use code like this:
var span = document.getElementById("span_id");
var inputs = span.getElementsByTagName("input");
for (var i = 0; i < inputs.length; ++i) {
if (inputs[i].checked) {
// ...
}
}
I can't be too sure what you mean but if you want to do something to all radio buttons on a page you can do this:
$("input:radio").each(function(){
//do something here
});

Categories