Reset form fields, set of fields using jQuery

Use case:

Let say we have a form and for a case we need reset it. In jQuery we can very easily do it by using following line:

$('form')[0].reset()

But in a case we have a form that has miltiple block fileds. We need one of the block to be reset but other fields should not be reset in the form.

Generic reset field function

We can very easily write a function and expose that to jQuery prototype. Following is the function:

$.fn.resetFields = function(){
    $(this).find(':input').not(':button, :submit, :reset, :hidden').val('').prop('checked', false).prop('selected', false);
};

What does the function do?

This resetFields function can be called on any DOM element. It will simply look for input element inside that DOM element and reset it. It will not reset the hidden, submit fields.

When we call $(‘form’)[0].reset() method from jQuery it runs similar methods behind the scene.

Share