Home > Blockchain >  How to clear input fields and prevent submission?
How to clear input fields and prevent submission?

Time:07-13

Im having a form with several input fields and im trying to do a js script that while i click on a button my inputs become empty and my form does not submit.

This is my form:

let btnClear = document.querySelector('button');
            
            let inputs = document.querySelector('inputs');
            
            btnClear.addEventListener('click', () => {
                inputs.forEach(input => input.value = ' ');
                    
            });
      
      
 let $departemento = document.getElementById('departamento')
         let $provincia = document.getElementById('provincia')
         let $distrito = document.getElementById('distrito')

         let departamentos = ['Argentina', 'Brasil']
         let provincias = ['Bs As', 'Cordoba', 'San Pablo']
         let distritos = ['San Miguel', 'San Nicolas', 'Tigre', 'Belgrano', 'Calamuchita', 'La falda', 'Gral Belgrano', 'Santa Marta', 'Loa Loa']

         function mostrarLugares(arreglo, lugar) {
             let elementos = '<option selected disables>--Seleccione--</option>'

             for(let i = 0; i < arreglo.length; i  ) {
                 elementos  = '<option value="'   arreglo[i]  '">'   arreglo[i]  '</option>'
             }

             lugar.innerHTML = elementos
         }

         mostrarLugares(departamentos, $departemento)

         function recortar(array, inicio, fin, lugar) {
             let recortar = array.slice(inicio, fin)
             mostrarLugares(recortar, lugar)
         }

         $departemento.addEventListener('change', function() {
             let valor = $departemento.value

             switch(valor) {
                 case 'Argentina':
                     recortar(provincias, 0, 2, $provincia)
                 break
                 case 'Brasil':
                     recortar(provincias, 2, 3, $provincia)
                 break
             }

             $distrito.innerHTML = ''
         })

         $provincia.addEventListener('change', function() {
             let valor = $provincia.value

             if(valor == 'Bs As') {
                 recortar(distritos, 0, 4, $distrito)
             } else if(valor == 'Cordoba') {
                 recortar(distritos, 4, 7, $distrito)
             } else {
                 recortar(distritos, 7, 9, $distrito)
             }
         })
         
         
   <div >
          <div >
            <div >
             <form  method="post" action="ServletPacientes">
              
                <h1  >Ingresar nuevo paciente</h1>
                <div >
                <div >
                  <div> 
                  <label>Nombre:</label> 
                  <input type="text" onkeypress="return checkLetras(event)"  name="txtNombre" title="Ingrese su nombre" required /> </div>
                </div>
                <div >             
                  <div>
                  <label>Apellido:</label> 
                  <input type="text" onkeypress="return checkLetras(event)"  name="txtApellido" required="">
                  </div>
                </div>
                
                <div >
                  <label>DNI: </label>
                  <input type="text" onkeypress="return check(event)" maxlength="8" minlength="7"  name="txtDNI" required>
                </div>
                <div >
                  <label>Correo electrónico: </label>
                  <input type="email"  name="txtCorreo" required>
                </div>
                
                
                
                <div >
                  <label>Teléfono: </label>
                  <input type="text" onkeypress="return check(event)"  name="txtTelefono" required>
                </div>
                                                
                <div >
                  <label>Fecha de nacimiento: </label>
                  <input type="date"  name="txtFechaNac" required>
                </div>
             
                
                 <div >
                        <label for="departamento" > Nacionalidad</label>
                        <select name="comboNacionalidad" id="departamento" >
                            <!-- cargaremos las etiquetas de option con javascript -->
                        </select>
                    </div>
      
                <div >
                    <label for="provincia"> Provincias</label>
                    <select name="comboProvincia" id="provincia" >
                        <!-- cargaremos las etiquetas de option con javascript -->
                    </select>
                </div>    
    
                    <div >
                        <label for="distrito" > Localidades</label>
                        <select name="comboLocalidad" id="distrito" >
                            <!-- cargaremos las etiquetas de option con javascript -->
                        </select>
                    </div>                             
                
                <div >
                    <input onclick="confirmarAgregar(event)"  type="submit"  value="Aceptar" name="btnAceptar">
                    <button  type="" >Limpiar campos</button>
                </div>
               </div> 
              </form>
              
              
            </div>
          </div>
         </div>

For some reason my form is being submitted and redirecting me to another page and my texts are never emptying. I took the submit type to my but and still does not work.

CodePudding user response:

The confirmAgregar function, wherever it's defined, needs to be updated as so:

function confirmAgregar(event){
  event.preventDefault()
  // ... rest of your code
}

The default behavior of an HTML form submission event is to refresh the page. When you use JavaScript to handle the form submission, you usually want to prevent that behavior, then let your handle submit function perform whatever logic your form needs to do.

CodePudding user response:

For preventing form submit you need to call preventDefault() on form submit event:

<form  method="post" action="ServletPacientes" onsubmit="event.preventDefault()">
  ...
</form>

For clearing inputs you need to set correct tag name, select them all and make array to iterate them:

let inputs = [...document.querySelectorAll('input')]; 

Or you can just reset all your form:

const form = document.querySelector("form");
form.reset(); // reset all inputs and form elements inside this form
  • Related