简体   繁体   English

清除 HTML 中的 2 个文本字段

[英]Clear 2 Textfield in HTML

I'm trying to write a simple HTML code to clear 2 textboxes once the Clear Text button is clicked.我正在尝试编写一个简单的 HTML 代码,以在单击“清除文本”按钮后清除 2 个文本框。 Now it only clears 1 text field instead of 2. How can I make it so that it clears both at the same time?现在它只清除 1 个文本字段而不是 2 个。我怎样才能使它同时清除两个?

<script>
        function swapValues() {
            var tmp = document.getElementById("a").value;
            document.getElementById("a").value = document.getElementById("b").value;
            document.getElementById("b").value = tmp;
        }
        function clear() {
            var clearA = document.getElementById('a').value = '';
            var clearB = document.getElementById('b').value = '';

            if (clearA != " " && clearB != " "){
                document.getElementById('myInput').value = ''
            }
        }
</script>

HTML: HTML:

<body>

<input type="text" id="a" value="John" /><br><br>
<input type="text" id="b" value="Lee" /><br><br>

<input type="button" id="go" onclick="swapValues()" value="Swap">

<button onclick="document.getElementById('a').value = ''">Clear Text</button>

Concatenate both clear actions with ;;连接两个明确的动作:

   onclick="document.getElementById('a').value = ''; document.getElementById('b').value = ''; "

Why you are assigning the none output to another variable?为什么要将 none output 分配给另一个变量?

function clear() {
            document.getElementById('a').value = '';
            document.getElementById('b').value = '';

            if (document.getElementById('a').value != " " && document.getElementById('b').value != " "){
                document.getElementById('myInput').value = ''
            }
        }

And set onClick to call clear() :并设置onClick调用clear()

<button onclick="clear();">Clear Text</button>

Even after correcting the errors in your code, the "clear()" function will not run.即使更正了代码中的错误,“clear()”function 也不会运行。 Clear is not a saved keyword.清除不是已保存的关键字。 But most likely there is a conflict withdocument.clear();但很可能与document.clear();存在冲突。 . . Therefore, it is necessary to change the name of this function to work correctly.因此,需要更改此 function 的名称才能正常工作。

Example:例子:

 function swapValues() { var tmp = document.getElementById("a").value; document.getElementById("a").value = document.getElementById("b").value; document.getElementById("b").value = tmp; } function clearValue() { var clearA = document.getElementById('a'); var clearB = document.getElementById('b'); clearA.value = ''; clearB.value = ''; if (clearA.value.= '' && clearB.value;= '') { console.log('some action'); } }
 <input type="text" id="a" value="John" /><br><br> <input type="text" id="b" value="Lee" /><br><br> <input type="button" id="go" onclick="swapValues()" value="Swap"> <button onclick="clearValue()">Clear Text</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM