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

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

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.

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");
}
});
});

Execute custom function onChange

Pure JavaScript.
I have a checkbox in HTML page. I want to execute
App.setCheckedProperty(name, val);
Where name is name attribute of the checkbox and val true/false means checked.
How to implement it? I can't find any materials aboit it on the Net.
UPD:
<input type="checkbox" name="smth" onChange="<WHAT TO DO HERE?>" checked />
Final execution must be equal:
App.setCheckedProperty("smth", false);
UPD2:
Are there any contructions like this.name or this.checked in JavaScript?
you shouldnt do it "inline" inside your html. its just bad practice. i think what you want to do is to loop over a couple of checkboxes?
see this code:
// declare all vars that you need and find all input-elements
var i, input, inputs = document.getElementsByTagName('input');
// loop over all input-elements
for(i = 0; i <= inputs.length; i++) {
input = inputs[i];
// if the current element is a checkbox
if(input.type === 'checkbox') {
//append a click-handler to that checkbox
input.onclick = function () {
// if the checkbox is clicked, you can find the name and the checked-property
App.setCheckedProperty(this.name, this.checked);
};
}
}
and a working example here (i just alert instead of App.setCheckedProperty): http://jsfiddle.net/5wExJ/

Onsubmit validate change background requried fields?

Anyone know of a good tutorial/method of using Javascript to, onSubmit, change the background color of all empty fields with class="required" ?
Something like this should do the trick, but it's difficult to know exactly what you're looking for without you posting more details:
document.getElementById("myForm").onsubmit = function() {
var fields = this.getElementsByClassName("required"),
sendForm = true;
for(var i = 0; i < fields.length; i++) {
if(!fields[i].value) {
fields[i].style.backgroundColor = "#ff0000";
sendForm = false;
}
else {
//Else block added due to comments about returning colour to normal
fields[i].style.backgroundColor = "#fff";
}
}
if(!sendForm) {
return false;
}
}
This attaches a listener to the onsubmit event of the form with id "myForm". It then gets all elements within that form with a class of "required" (note that getElementsByClassName is not supported in older versions of IE, so you may want to look into alternatives there), loops through that collection, checks the value of each, and changes the background colour if it finds any empty ones. If there are any empty ones, it prevents the form from being submitted.
Here's a working example.
Perhaps something like this:
$(document).ready(function () {
$('form').submit(function () {
$('input, textarea, select', this).foreach(function () {
if ($(this).val() == '') {
$(this).addClass('required');
}
});
});
});
I quickly became a fan of jQuery. The documentation is amazing.
http://docs.jquery.com/Downloading_jQuery
if You decide to give the library a try, then here is your code:
//on DOM ready event
$(document).ready(
// register a 'submit' event for your form
$("#formId").submit(function(event){
// clear the required fields if this is the second time the user is submitting the form
$('.required', this).removeClass("required");
// snag every field of type 'input'.
// filter them, keeping inputs with a '' value
// add the class 'required' to the blank inputs.
$('input', this).filter( function( index ){
var keepMe = false;
if(this.val() == ''){
keepMe = true;
}
return keepMe;
}).addClass("required");
if($(".required", this).length > 0){
event.preventDefault();
}
});
);

You need to select at least one radio button / checkbox

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)) {
// …
}

Categories