Borrar campos de formulario con jQuery


Quiero borrar todos los campos input y textarea en un formulario. Funciona de la siguiente manera cuando se usa un botón de entrada con la clase reset:

$(".reset").bind("click", function() {
  $("input[type=text], textarea").val("");
});

Esto borrará todos los campos de la página, no solo los del formulario. ¿Cómo se vería mi selector solo para la forma en la que vive el botón de reinicio real?

Author: Elnur Abdurrakhimov, 2011-06-16

27 answers

$(".reset").click(function() {
    $(this).closest('form').find("input[type=text], textarea").val("");
});
 414
Author: ShaneBlake,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-06-15 21:04:06

Para jQuery 1.6+:

$(':input','#myform')
  .not(':button, :submit, :reset, :hidden')
  .val('')
  .prop('checked', false)
  .prop('selected', false);

Para jQuery :

$(':input','#myform')
  .not(':button, :submit, :reset, :hidden')
  .val('')
  .removeAttr('checked')
  .removeAttr('selected');

Por favor vea este post: Restablecer un formulario de varias etapas con jQuery

O

$('#myform')[0].reset();

Como jQuery sugiere :

Para recuperar y cambiar las propiedades del DOM, como checked, selected, o disabled estado de los elementos de forma, utilice el .prop () método.

 555
Author: ngen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-26 01:45:55

¿Alguna razón por la que esto no debería usarse?

$("#form").trigger('reset');
 139
Author: user768680,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-17 18:45:57

Esto no manejará los casos en los que los campos de entrada del formulario no tengan valores predeterminados vacíos.

Algo así debería funcionar

$('yourdiv').find('form')[0].reset();
 57
Author: parapura rajkumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-06-15 21:03:43

Si usa selectores y hace que los valores se vacíen, no está restableciendo el formulario, está vaciando todos los campos. Reset es hacer el formulario como estaba antes de cualquier acción de edición del usuario después de la carga del formulario desde el lado del servidor. Si hay una entrada con el nombre "username" y ese nombre de usuario se rellenó previamente desde el lado del servidor, la mayoría de las soluciones en esta página eliminarán ese valor de la entrada, no lo restablecerán al valor como estaba antes de los cambios del usuario. Si necesita restablecer el formulario, utilice esto:

$('#myform')[0].reset();

Si no necesita restablecer el formulario, sino llenar todas las entradas con algún valor, por ejemplo, un valor vacío, entonces puede usar la mayoría de las soluciones de otros comentarios.

 44
Author: Lukas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-18 18:30:11

Simple pero funciona como un encanto.

$("#form").trigger('reset'); //jquery
document.getElementById("myform").reset(); //native JS
 28
Author: jroi_web,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-03 04:24:59

Si alguien todavía está leyendo este hilo, aquí está la solución más simple usando no jQuery, sino JavaScript simple. Si sus campos de entrada están dentro de un formulario, hay un simple comando de restablecimiento de JavaScript:

document.getElementById("myform").reset();

Más sobre esto aquí: http://www.w3schools.com/jsref/met_form_reset.asp

Salud!

 27
Author: Tarmo Saluste,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-03 08:29:33
$('form[name="myform"]')[0].reset();
 20
Author: apen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-01 03:53:59

¿Por qué hay que hacerlo con JavaScript?

<form>
    <!-- snip -->
    <input type="reset" value="Reset"/>
</form>

Http://www.w3.org/TR/html5/the-input-element.html#attr-input-type-keywords


Probó eso primero, no borrará los campos con valores predeterminados.

Aquí hay una manera de hacerlo con jQuery, entonces:

$('.reset').on('click', function() {
    $(this).closest('form').find('input[type=text], textarea').val('');
});
 15
Author: Matt Ball,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-27 14:36:51

Tengo el truco más fácil para restablecer la forma

jQuery("#review-form")[0].reset();

O

$("#review-form").get().reset();
 11
Author: mumair,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-17 10:04:36

Si desea vaciar todas las cajas de entrada independientemente de su tipo, entonces es un paso de un minuto por

 $('#MyFormId')[0].reset();
 11
Author: sunshine,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-01 12:43:16

Con Javascript simplemente puede hacerlo con esta sintaxis getElementById("your-form-id").reset();

También puede usar jquery llamando a la función de restablecimiento de esta manera $('#your-form-id')[0].reset();

Recuerda no olvidar [0]. Obtendrá el siguiente error si

TypeError: $(...).reset no es una función

JQuery también proporciona un evento que puede usar

$('#form_id').trigger ("reset");

Lo intenté y funciona.

Nota: es importante notar que estos métodos solo restablezca su formulario a su valor inicial establecido por el servidor al cargar la página. Esto significa que si su entrada se estableció en el valor 'set value' antes de hacer un cambio aleatorio, el campo se restablecerá a ese mismo valor después de que se llame al método de restablecimiento.

Espero que ayude

 10
Author: BoCyrill,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-01 18:36:01
$('#editPOIForm').each(function(){ 
    this.reset();
});

Donde editPOIForm es el atributo id de tu forma.

 6
Author: Knowledge Serve,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-17 12:01:12

¿Por qué no usas document.getElementById("myId").reset(); ? este es el simple y bonito

 5
Author: Carlos Alvarez,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-23 13:02:18

Código probado y verificado:

  $( document ).ready(function() {
    $('#messageForm').submit(function(e){
       e.preventDefault();
    });
    $('#send').click(function(e){
      $("#messageForm")[0].reset();
    });
  });

Javascript debe estar incluido en $(document).ready y debe estar con su lógica.

 5
Author: DeepCode,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-02 11:40:51

Yo uso esto:

$(".reset").click(function() {
  $('input[type=text]').each(function(){
     $(this).val('');
  });
});

Y aquí está mi botón:

<a href="#" class="reset">
  <i class="fa fa-close"></i>
     Reset
</a>
 3
Author: Matheno,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-17 10:46:47

Digamos que si desea borrar los campos y excepto AccountType,en el tiempo medio el cuadro desplegable se restablecerá a un valor particular,es decir, 'Todo'.Los campos restantes deben restablecerse a un cuadro de texto vacío, es decir.Este enfoque se utilizará para despejar campos particulares como nuestro requisito.

 $(':input').not('#accountType').each( function() {

    if(this.type=='text' || this.type=='textarea'){
             this.value = '';
       }
    else if(this.type=='radio' || this.type=='checkbox'){
         this.checked=false;
      }
         else if(this.type=='select-one' || this.type=='select-multiple'){
              this.value ='All';
     }
 });
 2
Author: Gnanasekaran Ebinezar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-05-31 09:09:12

La solución más fácil y mejor es-
$("#form")[0].reset();

No utilice aquí -
$(this)[0].reset();

 2
Author: Mamun Sabuj,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-19 07:40:19

Utilice este Código donde desea Llamar a la Función de Restablecimiento Normal mediante jQuery

setTimeout("reset_form()",2000);

Y Escriba esta Función en el Sitio jQuery en Document Ready

<script>
function reset_form()
{
    var fm=document.getElementById('form1');
    fm.reset();
}
</script>
 1
Author: Monzur,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-04-22 20:33:44
@using (Ajax.BeginForm("Create", "AcceptanceQualityDefect", new AjaxOptions()
{
    OnSuccess = "ClearInput",
    HttpMethod = "Post",
    UpdateTargetId = "defect-list",
    InsertionMode = InsertionMode.Replace
}, new { @id = "frmID" })) 
  1. frmID es la identificación de la forma
  2. OnSuccess de la operación llamamos a la función JavaScript con el nombre "ClearInput"

    <script type="text/javascript">
        function ClearInput() {
            //call action for render create view
            $("#frmID").get(0).reset();
        }
    </script>
    
  3. Si haces ambos bien, entonces no podrás evitar que funcione...

 1
Author: L.W.C. Nirosh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-14 13:04:54

Si quiero borrar todos los campos excepto AccountType..Utilice el siguiente

$q(':input','#myform').not('#accountType').val('').removeAttr('checked').removeAttr('selected');
 0
Author: Gnansekaran Ebinezar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-05-29 11:39:42

El código que veo aquí y en las preguntas relacionadas por lo que parece incompleto.

Restablecer un formulario significa establecer los valores originales desde el HTML, así que armé esto para un pequeño proyecto que estaba haciendo basado en el código anterior:

            $(':input', this)
                .not(':button, :submit, :reset, :hidden')
                .each(function(i,e) {
                    $(e).val($(e).attr('value') || '')
                        .prop('checked',  false)
                        .prop('selected', false)
                })

            $('option[selected]', this).prop('selected', true)
            $('input[checked]',   this).prop('checked',  true)
            $('textarea',         this).each(function(i,e) { $(e).val($(e).html()) })

Por favor, hágamelo saber si me falta algo o cualquier cosa se puede mejorar.

 0
Author: Rafael Kitover,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-28 20:22:05

Nada de lo anterior funciona en un caso simple cuando la página incluye una llamada al control de usuarios web que involucra el procesamiento de solicitudes de IHttpHandler (captcha). Después de enviar el requsrt (para el procesamiento de imágenes) el código a continuación no borra los campos en el formulario (antes de enviar la solicitud HttpHandler ) todo funciona correctamente.

<input type="reset"  value="ClearAllFields" onclick="ClearContact()" />

 <script type="text/javascript">
       function ClearContact() {
           ("form :text").val("");
       }
    </script>
 0
Author: user2366666,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-09 14:29:03

He escrito un plugin jQuery universal:

/**
 * Resets any input field or form
 */
$.fn.uReset = function () {
    return this.filter('form, :input').each(function () {
        var input = $(this);
        
        // Reset the form.
        if (input.is('form')) {
            input[0].reset();
            return;
        }

        // Reset any form field.
        if (input.is(':radio, :checkbox')) {
            input.prop('checked', this.defaultChecked);
        } else if (input.is('select')) {
            input.find('option').each(function () {
                $(this).prop('selected', this.defaultSelected);
            });
        } else if (this.defaultValue) {
            input.val(this.defaultValue);
        } else {
            console.log('Cannot reset to default value');
        }
    });
};

$(function () {
    // Test jQuery plugin.
    $('button').click(function (e) {
        e.preventDefault();
        
        var button = $(this),
            inputType = button.val(),
            form = button.closest('form');
        
        if (inputType === 'form') {
            form.uReset()
        } else {
            $('input[type=' + inputType + '], ' + inputType, form).uReset();
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h3>Form</h3>
<form>
    <input type="text" value="default"/><br /><br />
    Ch 1 (default checked) <input type="checkbox" name="color" value="1" checked="checked" /><br />
    Ch 2 <input type="checkbox" name="color" value="2" /><br />
    Ch 3 (default checked) <input type="checkbox" name="color" value="3" checked="checked" /><br /><br />
    <select name="time"><br />
        <option value="15">15</option>
        <option selected="selected" value="30">30</option>
        <option value="45">45</option>
    </select><br /><br />
    R 1 <input type="radio" name="color" value="1" /><br />
    R 2 (default checked) <input type="radio" name="color" value="2" checked="checked" /><br />
    R 3 <input type="radio" name="color" value="3" /><br /><br />
    <textarea>Default text</textarea><br /><br />
    
    <p>Play with form values and then try to reset them</p>
    
    <button type="button" value="text">Reset text input</button>
    <button type="button" value="checkbox">Reset checkboxes</button>
    <button type="button" value="select">Reset select</button>
    <button type="button" value="radio">Reset radios</button>
    <button type="button" value="textarea">Reset textarea</button>
    <button type="button" value="form">Reset the Form</button>
</form>
 0
Author: Jekis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-30 23:15:22

El siguiente código borra todo el formulario y sus campos estarán vacíos. Si desea borrar solo un formulario en particular si la página tiene más de un formulario, mencione el id o la clase del formulario

$("body").find('form').find('input,  textarea').val('');
 0
Author: shivaP,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-04 11:19:52

Agregue el botón de reinicio oculto de la siguiente manera

<input id="resetBtn" type="reset" value="reset" style="display:none" />
// Call reset buttons click event
// Similar to ClearInputs('resetBtn');
function ClearInputs(btnSelector) {
     var btn = $("#" + btnSelector);
     btn.click();
}
 -3
Author: Jayan.C.A,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-05 10:25:38

$("formulario").enviar (function () {

var el = $(this);

$('<button type="reset" style="display:none; "></button>')
    .appendTo(el)
    .click()
    .remove()
;

return false;

});

 -3
Author: Júnior Mendonça,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-04-19 13:04:33