如何用值替换空的输入字段

时间:2019-01-21 16:35:19

标签: javascript html input

我想用on_click底部的值“ 0”替换一个空的输入文件,而在输入文件中看不到新的值“ 0”。

      <input type="number" id="myText"onfocus="if (this.value=!'') this.value='';" min="0" oninput="this.value = Math.abs(this.value)"/>
    <br/> <p  </p><input type="number" id="myletter"value="3" onfocus="if (this.value=!'') this.value='';" min="0" oninput="this.value = Math.abs(this.value)"/>
    <br/> <p <input  type="number" id="mycapitalletter" value="1" onfocus="if (this.value=!'') this.value='';" min="0" oninput="this.value = Math.abs(this.value)"/>       
    <br/> <p  <input  type="number" id="sc""value="0" onfocus="if (this.value=!'') this.value='';" min="0" oninput="this.value = Math.abs(this.value)"/>
    <br/>
       <br/>
       <button onclick="myFunction()">click</button>

1 个答案:

答案 0 :(得分:0)

因此,基本上,您需要做的是在所有输入元素中修复onfocus="if (this.value=!'') this.value='';,主要是因为您错误地声明了等号运算符,因此您拥有=!而不是!==或{{1 }}。这是固定的html:

!=

或者最终您可以跳过手动将其添加到每个输入的操作,并在元素下方创建<input type="number" id="myText" onfocus="if (this.value!=='') this.value='';" min="0" oninput="this.value = Math.abs(this.value)" /> <br/> <p> <input type="number" id="myletter" value="3" onfocus="if (this.value!=='') this.value='';" min="0" oninput="this.value = Math.abs(this.value)" /> </p> <br/> <p> <input type="number" id="mycapitalletter" value="1" onfocus="if (this.value!=='') this.value='';" min="0" oninput="this.value = Math.abs(this.value)" /> </p> <br/> <p> <input type="number" id="sc" value="0" onfocus="if (this.value!=='') this.value='';" min="0" oninput="this.value = Math.abs(this.value)" /> </p> <br/> <br/> <button onclick="myFunction()">click</button>标签,如下所示:

<script> </script>

如我所说,脚本的作用是遍历<input type="number" id="myText" min="0" oninput="this.value = Math.abs(this.value)" /> <br/> <p> <input type="number" id="myletter" value="3" min="0" oninput="this.value = Math.abs(this.value)" /> </p> <br/> <p> <input type="number" id="mycapitalletter" value="1" min="0" oninput="this.value = Math.abs(this.value)" /> </p> <br/> <p> <input type="number" id="sc" value="0" min="0" oninput="this.value = Math.abs(this.value)" /> </p> <br/> <br/> <button onclick="myFunction()">click</button> <script type="text/javascript"> const inputs = document.querySelectorAll('input'); inputs.forEach((input, i) => { input.onfocus = (event) => { event.currentTarget.value = ""; } }); </script>返回的HtmlCollection。然后附加一个简单的函数,将querySelector事件的input的值设置为空(或空字符串)。