[英]How to clear an input with javascript?
I have 3 inputs: 我有3个输入:
<label for="text1">Text 1</label>
<input type="text" class="text1" value="To clear"><br>
<label for="text2">Text 2</label>
<input type="text" class="text2" value="to select"><br>
<label for="text3">Text 3</label>
<input type="text" class="text3" value="Click in this field">
I would like that when you click in the text3, it erases the text1. 我希望当你点击text3时,它会删除text1。 I did a function but it does not work:
我做了一个功能,但它不起作用:
<script>
function myFunction(text3) {
document.text1.value = "";
}
</script>
The correct way of doing this is to assign an event listener to the element, within that you can call your function 执行此操作的正确方法是为元素分配一个事件侦听器,您可以在其中调用您的函数
function myFunction() { document.querySelector('input.text1').value = ""; } document.querySelector('input.text3').addEventListener('focus', myFunction);
<label for="text1">Text 1</label> <input type="text" class="text1" value="To clear"><br> <label for="text2">Text 2</label> <input type="text" class="text2" value="to select"><br> <label for="text3">Text 3</label> <input type="text" class="text3" value="Click in this field">
Make sure to select your elements with DOM methods like querySelector
, getElement(s)By...
and so on. 确保使用DOM方法选择元素,如
querySelector
, getElement(s)By...
等等。 Never rely on accessing an element by it's global id as this may break depending on used browser. 永远不要依赖于通过它的全局ID访问元素,因为这可能会因使用的浏览器而中断。 (Though
document.text1.value = "";
will never work..) (虽然
document.text1.value = "";
永远不会工作..)
var text1 = document.querySelector('.text1'); var text3 = document.querySelector('.text3'); text3.addEventListener('focus', myFunction); function myFunction() { text1.value = ''; }
<label for="text1">Text 1</label> <input type="text" class="text1" value="To clear"><br> <label for="text2">Text 2</label> <input type="text" class="text2" value="to select"><br> <label for="text3">Text 3</label> <input type="text" class="text3" value="Click in this field">
You can do it very easily using JQuery . 你可以使用JQuery轻松完成。
$('.text3').on('focus', function() { $('.text1').val(''); })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <label for="text1">Text 1</label> <input type="text" class="text1" value="To clear"><br> <label for="text2">Text 2</label> <input type="text" class="text2" value="to select"><br> <label for="text3">Text 3</label> <input type="text" class="text3" value="Click in this field">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.