In my form, I want to enable form only when all fields (and radio button list) has been selected.
So far, I have successfully made the submit button enable
There are a few different ways to go about this (as you've likely seen above).
This probably isn't the most efficient way, but you could check every time they click or press a key to see if any of the text fields are empty and if any of the radio buttons are filled. If one radio button is filled and none of the text fields are empty, you can go ahead and enable the button. Otherwise, you can disable it (or leave it disabled).
Let's go line by line:
function check() { // Define a function that we can call our event listeners with
// Get our inputs and textareas
var inputs = document.getElementsByTagName("input");
var textareas = document.getElementsByTagName("textarea");
var filled = true; // We'll assume that all of the fields are full unless proven otherwise
var oneChecked = false; // We can use this to keep track of the radio buttons (by assuming at first that none are checked)
for (var i = 0; i < inputs.length; i++) { // Loop through all of the inputs first
if (inputs[i].type === "text" && !inputs[i].value) { // If the input is a text field, check whether it is empty; if so, set filled to false
filled = false;
}
if (inputs[i].type === "radio" && inputs[i].checked) { // If the input is a radio button, see if it is filled in; because we only need one radio button to be filled in, that's all we need to know
oneChecked = true;
}
}
if (!oneChecked) { // Check outside of the loop if any of our radio buttons were selected and, if not, set filled to false
filled = false;
}
for (var j = 0; j < textareas.length; j++) { // Now loop through all of the text areas; if any aren't filled in, set filled to false
if (!textareas[j].value) {
filled = false;
}
}
if (filled) { // Check whether any of the fields are empty (or, in the radio button's case, if one is selected, and enable/disable the button accordingly
document.getElementById("subnewtopic").disabled = false;
} else {
document.getElementById("subnewtopic").disabled = true;
}
}
// Add event listeners to check for keypresses and clicks
window.addEventListener("keyup", check);
window.addEventListener("click", check);
Demo