Reputation: 6480
I have JavaScript which checks for text fields and check boxes fine but when comes to radio buttons it fails to distinguish if one of the options was selected.
How to do this correctly?
This is what I have:
validateBugForm = function()
{
var name = document.forms["bug_form"]["Name"].value;
var email = document.forms["bug_form"]["Email"].value;
var tos = document.forms["bug_form"]["Accept"].checked;
var project = document.forms["bug_form"]["project"].value;
if (name == "")
{
alert("You must provide your name or nick name!");
return false;
}
if (project == "")
{
alert("You must choose a project.");
return false;
}
if (email.indexOf ('@', 0) == -1 || email.indexOf ('.', 0) == -1)
{
alert("You must provide your email address!");
return false;
}
if (!tos)
{
alert("You must agree to our Terms of Services.");
return false;
}
}
In my form I have:
<tr>
<td width="30%">Choose a project in which you encountered a problem.
<big><font color="red">*</font></big></td></td>
<td width="10px" class="table_td_space"></td>
<td width="70%">
<input type="radio" name="project" value="1" id="1">1<br>
<input type="radio" name="project" value="2" id="2">2<br>
<input type="radio" name="project" value="3" id="3">3<br>
<input type="radio" name="project" value="4" id="4">4<br>
</td>
</tr>
Upvotes: 0
Views: 16927
Reputation: 530
You can do a querySelectorAll by input type. This will give you a node list. Then you can convert it to an array and loop though each input, and add an eventLister on each radio button. If one is checked, you can show validation valid, else call a showError function. But, radio-check boxes naturally can only be checked one at a time, so you'd have to show the error from the start before anything is selected, or you can call another function on submit to stop submission with preventDefault()
if no radio box is selected. If you are getting those radio-box values from a database in your view, you should inspect the element and replace the JS selectors appropriately. This example is static html but can easily be implemented from queried database fields. You will need an action too.
const projectIdsNodeList = document.querySelectorAll("input[type=radio]"); // Get node list
const projectIdsArr = Array.prototype.slice.call(projectIdsNodeList); // convert to array
const projectIdsError = document.getElementById("project-ids-error"); // The static div in the html
const form = document.getElementById("project-form"); // The form
let isValid = false; // true or false
projectIdsArr.forEach((project, index) => {
project.addEventListener("input", (event) => {
if(project.checked) {
projectIdsError.textContent = "Great Job!";
projectIdsError.className = "valid-custom-styles";
isValid = true;
} else {
isValid = false;
}
});
});
form.addEventListener("submit", (event) => {
if(!isValid) {
showError();
alert("you must select a project")
event.preventDefault();
}
});
function showError() {
if(!isValid) {
projectIdsError.textContent = "Please select a project!";
projectIdsError.className = "not-valid-custom-styles";
}
}
.not-valid-custom-styles {
color: red;
}
.valid-custom-styles {
color: green;
}
<form action="" id="project-form">
<p>Choose a project in which you encountered a problem:</p>
<input type="radio" name="project_ids" value="Project One" id="1">
<label>Project One</label><br>
<input type="radio" name="project_ids" value="Project Two" id="2">
<label>Project Two</label><br>
<input type="radio" name="project_ids" value="Project Three" id="3">
<label>Project Three</label><br>
<input type="radio" name="project_ids" value="Project Four" id="4">
<label>Project Four</label>
<br><br>
<div id="project-ids-error">Please select a project!</div>
<br>
<input type="submit" value="Submit">
</form>
Upvotes: 1
Reputation: 21
You need to loop through all of the radio button options to see if one was selected but when you holding the "projectObj" you have to call "value" method...
var projectObj = document.form1.project.value;
var len = projectObj.length;
var chosen = null;
for (i = 0; i <len; i++) {
if (projectObj[i].checked) {
chosen = projectObj[i].value;
}
}
if (chosen == null) {enter code here
alert("No Radio Button Chosen");
}
then it will take value otherswise it just return radio object list
Upvotes: 1
Reputation: 61
Just a note, I spent an hour scratching my head over this one because this works fine unless you are trying to validate a form with more than this radio element. Since each radio button is a separate form element and you are trying to loop through all the elements in the form (eg., everything with "required_" in the name), this might mess up the rest of the validation or cause it to always come up "false" since you end up checking each radio button as a separate element as you loop through the form. The way around this I found is to use a hidden form field to hold the value of the selected radio button by putting an onClick event on each radio button to transfer it's value to the hidden field when clicked - and just check that there is a value in that hidden field. And don't flag the radio button as an element to be checked.
Upvotes: 1
Reputation: 4524
You need to loop through all of the radio button options to see if one was selected:
var projectObj = document.form1.project
var len = projectObj.length
var chosen = null;
for (i = 0; i <len; i++) {
if (projectObj[i].checked) {
chosen = projectObj[i].value
}
}
if (chosen == null) {
alert("No Radio Button Chosen")
}
http://homepage.ntlworld.com/kayseycarvey/jss3p11.html
Upvotes: 6