最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Form's reset() method doesn't reset input with value attribute - Stack Overflow

programmeradmin0浏览0评论

Why second input with value attribute not being reset when I call the form's reset() method? And what is the best way to clean a form which has inputs with value attributes?

<form id="myform">
  <input type="text" />
  <input type="text" value="1" />
  <button id="reset" name="reset" onclick="document.getElementById('myform').reset()">reset</button>
</form>

Why second input with value attribute not being reset when I call the form's reset() method? And what is the best way to clean a form which has inputs with value attributes?

<form id="myform">
  <input type="text" />
  <input type="text" value="1" />
  <button id="reset" name="reset" onclick="document.getElementById('myform').reset()">reset</button>
</form>

Share Improve this question edited Aug 19, 2019 at 14:21 f0ks asked Aug 19, 2019 at 14:17 f0ksf0ks 471 silver badge4 bronze badges 2
  • DId you forget to put myform as ID in the above code? – Huangism Commented Aug 19, 2019 at 14:19
  • @Huangism yes I did. But still not working. – f0ks Commented Aug 19, 2019 at 14:22
Add a ment  | 

4 Answers 4

Reset to default 2

You don't need JavaScript here. Just set the type attribute of the button to reset.

<form>
  <input type="text" />
  <input type="text" value="1" />
  <button id="reset" name="reset" type="reset">reset</button>
</form>

By default, a button element within a form will submit the form.

Using JQuery

$("#reset").on("click" , function() {
   $("input[type=text]").val("");
});
<script src="https://cdnjs.cloudflare./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <input type="text" />
  <input type="text" value="1" />
  <button id="reset" name="reset" type="button">reset</button>
</form>

Reset button reset form to initial values, not empty values. If you want to reset form pletely, you should use empty form and then set values manually after form is placed to document. For example, apply ids to field you want to preset and then use something like

const filedValues = [{
    id: 'name',
    value: '1'
  },
  {
    id: 'text',
    value: 'test text'
  }
];
filedValues.forEach(fieldItem => {
  const {
    id,
    value
  } = fieldItem;
  document.getElementById(id).value = value;
})
<form>
  <input type="text" id="name" name="name" />
  <input type="text" name="text" id="text" />
  <button id="reset" name="reset" type="reset">reset</button>
</form>

Only one line code:

this.form.querySelectorAll('input[type=text]').forEach(function(input,i){input.value='';})

See:

<form>
  <input type="text" value="0"/>
  <input type="text" value="1" />
  <button id="reset" name="reset" onclick="this.form.querySelectorAll('input[type=text]').forEach(function(input,i){input.value='';})">reset</button>
</form>

Note: no need to add type=reset to button

发布评论

评论列表(0)

  1. 暂无评论