jQuery: Clearing Form Inputs

前端 未结 5 1580
灰色年华
灰色年华 2020-12-22 23:27

I have tried to different ways to clear a form:

First Name:
相关标签:
5条回答
  • 2020-12-23 00:00

    I'd recomment using good old javascript:

    document.getElementById("addRunner").reset();
    
    0 讨论(0)
  • 2020-12-23 00:04

    Demo : http://jsfiddle.net/xavi3r/D3prt/

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

    Original Answer: Resetting a multi-stage form with jQuery


    Mike's suggestion (from the comments) to keep checkbox and selects intact!

    Warning: If you're creating elements (so they're not in the dom), replace :hidden with [type=hidden] or all fields will be ignored!

    $(':input','#myform')
      .removeAttr('checked')
      .removeAttr('selected')
      .not(':button, :submit, :reset, :hidden, :radio, :checkbox')
      .val('');
    
    0 讨论(0)
  • 2020-12-23 00:15

    You may try

    $("#addRunner input").each(function(){ ... });
    

    Inputs are no selectors, so you do not need the : Haven't tested it with your code. Just a fast guess!

    0 讨论(0)
  • 2020-12-23 00:17

    I figured out what it was! When I cleared the fields using the each() method, it also cleared the hidden field which the php needed to run:

    if ($_POST['action'] == 'addRunner') 
    

    I used the :not() on the selection to stop it from clearing the hidden field.

    0 讨论(0)
  • 2020-12-23 00:21

    Took some searching and reading to find a method that suited my situation, on form submit, run ajax to a remote php script, on success/failure inform user, on complete clear the form.

    I had some default values, all other methods involved .val('') thereby not resetting but clearing the form.

    I got this too work by adding a reset button to the form, which had an id of myform:

    $("#myform > input[type=reset]").trigger('click');
    

    This for me had the correct outcome on resetting the form, oh and dont forget the

    event.preventDefault();
    

    to stop the form submitting in browser, like I did :).

    Regards

    Jacko

    0 讨论(0)
提交回复
热议问题