【问题标题】:How to clear contents of multiple <input>s by one button [duplicate]如何通过一个按钮清除多个<input>的内容[重复]
【发布时间】:2020-06-11 06:44:49
【问题描述】:
<input type="text" placeholder="A" id="A" autocomplete="off"/>
<input type="text" placeholder="B" id="B" autocomplete="off"/>

<button class="smallbutton" onclick="document.getElementsByTagName('input').value = ''">Clear</button>

我尝试使用getElementsByTagName,但它似乎不起作用。还需要做什么?或者除了TagName还能做什么?

【问题讨论】:

  • getElementsByTagName 返回一个节点列表。你需要迭代
  • 另外,如果在表单中,在按钮标签中添加 type="reset"
  • getElementsByWhatever 的更好替代方法是 document.querySelectorAll

标签: javascript html


【解决方案1】:

<input type="text" value="John"><br><br>
<input type="text" value="Doe"><br><br>

<button class="smallbutton" onclick="[...document.querySelectorAll('input[type=text]')].forEach(input => input.value = '')">Clear</button>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-01
    • 2019-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多