Resetting a multi-stage form with jQuery

2018-12-31 03:51发布

I have a form with a standard reset button coded thusly:

<input type="reset" class="button standard" value="Clear" />

Trouble is, said form is of the multi-stage sort, so if a user fills out a stage & then returns later, the 'remembered' values for the various fields won't reset when the Clear button is clicked.

I'm thinking that attaching a jQuery function to loop over all the fields and clear them 'manually' would do the trick. I'm already using jQuery within the form, but am only just getting up to speed & so am not sure how to go about this, other than individually referencing each field by ID, which doesn't seem very efficient.

TIA for any help.

30条回答
孤独总比滥情好
2楼-- · 2018-12-31 04:37

Modification of the most-voted answer for the $(document).ready() situation:

$('button[type="reset"]').click(function(e) {
    $form = $(this.form);
    $form.find('input:text, input:password, input:file, select, textarea').val('');
    $form.find('input:radio, input:checkbox').removeAttr('checked').removeAttr('selected');
    e.preventDefault();
});
查看更多
泪湿衣
3楼-- · 2018-12-31 04:38

You might find that this is actually easier solved without jQuery.

In regular JavaScript, this is as simple as:

document.getElementById('frmitem').reset();

I try to always remember that while we use jQuery to enhance and speed up our coding, sometimes it isn't actually faster. In those cases, it's often better to use another method.

查看更多
余生请多指教
4楼-- · 2018-12-31 04:40

jQuery Plugin

I created a jQuery plugin so I can use it easily anywhere I need it:

jQuery.fn.clear = function()
{
    var $form = $(this);

    $form.find('input:text, input:password, input:file, textarea').val('');
    $form.find('select option:selected').removeAttr('selected');
    $form.find('input:checkbox, input:radio').removeAttr('checked');

    return this;
}; 

So now I can use it by calling:

$('#my-form').clear();
查看更多
十年一品温如言
5楼-- · 2018-12-31 04:40

I find this works well.

$(":input").not(":button, :submit, :reset, :hidden").each( function() {
    this.value = this.defaultValue;     
});
查看更多
低头抚发
6楼-- · 2018-12-31 04:40

I was having the same problem and the post of Paolo helped me out, but I needed to adjust one thing. My form with id advancedindexsearch only contained input fields and gets the values from a session. For some reason the following did not work for me:

$("#advancedindexsearch").find("input:text").val("");

If I put an alert after this, I saw the values where removed correctly but afterwards they where replaced again. I still don't know how or why but the following line did do the trick for me:

$("#advancedindexsearch").find("input:text").attr("value","");
查看更多
浮光初槿花落
7楼-- · 2018-12-31 04:42

Clearing forms is a bit tricky and not as simple as it looks.

Suggest you use the jQuery form plugin and use its clearForm or resetForm functionality. It takes care of most of the corner cases.

查看更多
登录 后发表回答