Home > Software design >  How can I force a user to fill in input fields successively?
How can I force a user to fill in input fields successively?

Time:07-30

I am looking to create an input form that will force a user to enter something in each field successively before moving onto the next input or submitting. This is something that would be filled out by someone on a phone who is asking questions that are attached to each input field and recording the answer in the inputs. Thus to prevent someone from skipping/missing a question while on the phone, I want to require that each input field is filled out successively. For this reason, the HTML 'required' attribute does not necessarily work as it will only prevent submission if a field is not filled out.

Previously I have given each required input its own submit button, but this looks horrible and can be confusing for those who use it. What is the best way to achieve what I am looking do to using a combination of html, js, node, and/or ejs?

CodePudding user response:

Give each input a change event handler that makes the next input visible:

// Get all the labels into a node list
const labels = document.querySelectorAll("label");

// Get a reference to the last label
const lastLabel = labels[labels.length-1];

// Get a reference to a verification element
const output = document.querySelector("div.hidden");

// Use event delegation to handle all change events
document.addEventListener("change", function(event){
  // Get reference to the parent label of the changed element
  const lbl = event.target.closest("label");
  
  // Check to see if it's an element we care to handle
  if(lbl.classList.contains("response")){
  
    // Hide the changed label (and it's child input)
    lbl.classList.add("hidden");
    
    // Unhide the next label (and it's input child)
    lbl.nextElementSibling.classList.remove("hidden");
  }
  // If the current label was the last one
  if(lbl === lastLabel){
    // Show the verification field
    output.classList.remove("hidden")  
  }
});
.hidden { display:none; }
<label >#1<input ></label>
<label >#2<input ></label>
<label >#3<input ></label>
<div >DONE!</div>

  • Related