skip to Main Content
<form class="container" style="margin: 30px;">
        <input type="text" class="first-name" placeholder="first name">
        <input type="text" class="first-name" placeholder="last name">
        <button type="button">next</button>
    </form>
    <form class="container" style="margin: 30px;">
        <input type="radio" id="age1" name="age" value="30">
        <label for="age1">0 - 30</label><br>
        <input type="radio" id="age2" name="age" value="60">
        <label for="age2">31 - 60</label><br>
        <input type="radio" id="age3" name="age" value="100">
        <label for="age3">61 - 100</label><br><br>
        <input type="submit" value="Submit">
    </form>

I am creating a multi-step form and want the "Next" and "Submit" buttons to be active only when the input field are filled or selected. Can you help me with the right JS code?

3

Answers


  1. Use .value to check whether is undenied or not, if it’s undenied, set the button.disable=true, else button.disable=false. If the radio input, you can use input.check and find out whether the input is selected.

    Login or Signup to reply.
  2. You might try an approach like this – please see the comments throughout the code to indicate what is happening at that stage.

    /*
      delegated "change" event handler
      to process changes made within forms
    */
    document.addEventListener('change',e=>{
      if( e.target instanceof HTMLInputElement ){
        /*
          set a boolean that is used to determine if the button can be enabled.
          find the parent form and identify the button.
        */
        let valid=true;
        let form=e.target.closest('form');
        let bttn=form.querySelector('button');
        
        /*
          iterate through inputs ( note this might need to be modified if you have textarea etc )
          if any input is empty, change boolean to false and end processing.
          if all inputs are completed - proceed to enable button
        */
        let col=[ ...form.querySelectorAll('input') ];
            col.some(n=>{
              if( n.value=='' ){
                valid=false;
                return true
              }
            });
        if( valid && bttn )bttn.disabled=false;
      }
    });
    
    /*
      delegated "click" handler to process form button clicks
    */
    document.addEventListener('click',e=>{
      if( e.target instanceof HTMLButtonElement ){
        /*
          Find the parent form
        */
        let form=e.target.closest('form');
        /*
          Find ALL the forms in multi-stage process
          and deduce the number of them.
        */
        let col=[ ...document.querySelectorAll('form.container') ];
        let total=col.length - 1;
        
        /*
          Iterate through forms collection
          if it is NOT the final form, enable the next form and hide present
        */
        col.some((n,index)=>{
          if( n===form && index!=total ){
            col[ index + 1 ].classList.remove('hidden');
            form.classList.add('hidden');
            return true
          }
        });
      }
    });
    .hidden{display:none}
    form.container{margin: 30px;}
    label{display:block}
    label:last-of-type{margin:0 0 2rem 0;}
    <form class="container">
      <input type="text" class="first-name" placeholder="first name">
      <input type="text" class="first-name" placeholder="last name">
      <button type="button" disabled>next</button>
    </form>
    
    <form class="container hidden">
      <input type="text" name="gender" placeholder="teapot">
      <input type="text" name="iq" placeholder="2">
      <button type="button" disabled>next</button>
    </form>
    
    <form class="container hidden">
      <input type="text" name="colour" placeholder="green">
      <input type="text" name="size" placeholder="wheelbarrow">
      <button type="button" disabled>next</button>
    </form>
    
    
    <form class="container hidden">
      <label><input type="radio" name="age" value="30">0 - 30</label>
      <label><input type="radio" name="age" value="60">31 - 60</label>
      <label><input type="radio" name="age" value="100">61 - 100</label>
      <input type="submit" />
    </form>
    Login or Signup to reply.
  3. Extending my answer from here, the easiest way to do this would be to add a change event to the form. Then, for each button, you can check if the inputs have been filled out, and set the button’s .disabled accordingly. I’ve modified the original form to use some radios and multiple inputs for example purposes.

    To check if an <input> has been filled out, just take its .value, .trim() the string to get rid of unnecessary whitespace, then check if its length is 0. For radios, you can use a query selector to check if there are any elements of the radio’s name that have the checked attribute. If there are not, then it will return null. To combine these, just use the boolean OR (||)

    const next1 = document.querySelector('#next1');
    const next2 = document.querySelector('#next2');
    const submit = document.querySelector('#submit');
    
    const firstNameEl = document.querySelector('#firstName');
    const ageEl = document.querySelector('#age');
    const favNumEl = document.querySelector('#favnum');
    
    document.querySelector('#form1').addEventListener('change', e => {
      // example for single input field
      next1.disabled = firstNameEl.value.trim().length === 0;
      // example for two inputs
      next2.disabled = ageEl.value.trim().length === 0 || favNumEl.value.trim().length === 0;
      // example for radio
      submit.disabled = document.querySelector('input[name="good"]:checked') === null;
    });
    
    next1.addEventListener('click', e => {
      e.preventDefault();
      const firstName = firstNameEl.value;
      document.querySelectorAll('.firstName').forEach(el => el.textContent = firstName);
      document.querySelector('#section1').classList.toggle('hidden');
      document.querySelector('#section2').classList.toggle('hidden');
    });
    
    next2.addEventListener('click', e => {
      e.preventDefault();
      document.querySelector('#section2').classList.toggle('hidden');
      document.querySelector('#section3').classList.toggle('hidden');
    });
    .hidden {
      display: none;
    }
    <form id="form1" action="">
      <div id="section1">
        <input type="text" id="firstName" placeholder="First Name">
        <button id="next1" disabled>Next</button>
      </div>
      <br>
      <div id="section2" class="hidden">
        <p><span class="firstName"></span>, What's your age and favorite number?</p>
        <input type="number" id="age" placeholder="Your Age">
         <input type="number" id="favnum" placeholder="Favorite number">
        <button id="next2">Next</button>
      </div>
      <br>
      <div id="section3" class="hidden">
        <p>Are you doing good <span class="firstName"></span>?</p>
        <input type="radio" value="Yes" name="good">Yes
        <input type="radio" value="No" name="good">No
        <br>
        <button id="submit" class="submit">submit</button>
      </div>
    </form>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search