简体   繁体   中英

Multi Step Form Javascript

I am trying to create a multi step form for a website I am doing. The website is an autobody site, so theres a check box for services that a car would need. Such as oil change, tire rotation, echeck, and then other. Under "other", i have a text input box, but i don't want it to be active unless "other" is checked. With my current JS, I have it so the user can't go on to the next step of the form until all fields are filled in. But the code is detecting the "other" text box when it's not checked and wont let me go on to the next step. If someone could look at my code and see what I am doing wrong, that would be great.

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].value == "") {
      // add an "invalid" class to the field:
      y[i].className += " invalid";
      // and set the current valid status to false:
      valid = false;
    }
  }
  // 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
}

function fixStepIndicator(n) {
  // This function removes the "active" class of all steps...
  var i, x = document.getElementsByClassName("step");
  for (i = 0; i < x.length; i++) {
    x[i].className = x[i].className.replace(" active", "");
  }
  //... and adds the "active" class to the current step:
  x[n].className += " active";
}

//check box other
document.getElementById('other').onchange = function() {
 if(this.checked==true){
  document.getElementById("othertext").disabled=false;
  document.getElementById("othertext").focus();
 }
 else{
  document.getElementById("othertext").disabled=true;
 }
};

To me it looks like the problem is that you're getting all the inputs whether they're disabled or not, so you need to take that into account. Since you're using vanilla JS, you could do something like this with that IF condition in the validateForm function:

if (y[i].value == "" && y[i].disabled === false) {

This way it will only pick up the input fields that aren't disabled.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM