Call reset but outside of a FORM?

2019-09-04 15:50发布

I have a bunch of inputs, i'd like to call reset but there are all outside of a form. I tried calling reset on input and textarea with no luck.

Is there a similar function i can use?

3条回答
霸刀☆藐视天下
2楼-- · 2019-09-04 16:06

Keep in mind that the form RESET actually doesn't clear all fields, it will reset a form's default values back to default as well, so a better approach might be the following:

$('#the_form').trigger('reset');

Perhaps another approach:

// capture all existing values

var arr = [];

$(':input').each(function(i, e)
{
    arr.push($(e).val());
});

// custom function to reset all values to initially captured values

function my_reset()
{
    $(':input').each(function(i, e)
    {
        $(e).val(arr[i]);
    });
}

The above approach blindly targets all fields, if you have a way to better target them, you should definitely use what you can.

Additionally, this approach stores all the fields in order, so if you have dynamically generated fields, then this solution would have to be revised.

查看更多
相关推荐>>
3楼-- · 2019-09-04 16:14

Do you want to reset or just to clear the inputs? Reset would be more complicated, but clearing in your case is easy:

HTML:

  <input type="text"/>
  <textarea></textarea>
  <button id="resetBtn">Reset</button>

JS:

$("#resetBtn").click(function(){
  $("input, textarea").val("");
});
查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-09-04 16:16

My approach (second to putting them in a form...) would be to, onload, map the default values to each input id or name, and then create a reset method that just iterates that collection, get by id and set to default...

查看更多
登录 后发表回答