I'm building a tabbed for using a mixture of JavaScript and CSS. So far I have validation on my text inputs that ensure a user can't progress unless data has been input.
I have got it working so that my script detected unchecked checkboxes, but the problem is that I want the user to only select one. At the moment even when one gets selected the script won't let you progress because it's seeing the other three as unchecked. How could I add a rule to look at the checkboxes and set valid = true
if one is selected - if more or less than 1 then fail?
my function:
function validateForm() {
// This function deals with validation of the form fields
var x, y, i, valid = true;
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
// A loop that checks every input field in the current tab:
for (i = 0; i < y.length; i++) {
// If a field is empty...
if (y[i].type === "text") {
if (y[i].value == "") {
// add an "invalid" class to the field:
y[i].classList.add('invalid');
// and set the current valid status to false:
valid = false;
} else if (!y[i].value == "") {
y[i].classList.remove('invalid');
valid = true;
}
}
if (y[i].type === 'checkbox') {
if (!y[i].checked) {
y[i].classList.add('invalid');
valid = false;
} else if (y[i].checked) {
y[i].classList.remove('invalid');
valid = true;
}
}
}
// If the valid status is true, mark the step as finished and valid:
if (valid) {
document.getElementsByClassName("step")[currentTab].className += " finish";
}
return valid; // return the valid status
}
I have found some standalone scripts written such as:
function CheckForm(){
var checked=false;
var elements = document.getElementsByName("sel[]");
for(var i=0; i < elements.length; i++){
if(elements[i].checked) {
checked = true;
}
}
if (!checked) {
alert('Yada yada yada, some error message');
}
return checked;
}
But getting that to run alongside my text validation is just breaking my mind.
Aucun commentaire:
Enregistrer un commentaire