单击事件后清除输入值

时间:2016-08-09 18:31:38

标签: javascript javascript-events event-handling

我在javascript事件上遇到了一些麻烦。点击后我需要一些代码来清除输入值。输入被填充并列在“myTable”行中,然后输入字段变为空白

这是我的代码

<main>
<table>
    <tr>
        <td><input type="text" id="gds"></td>
        <td><input type="text" id="prc"></td>
        <td><input type="button" class="button" value="   + Add   " onclick="addField();"></td>
    </tr>
</table>
<table id="myTable">
</table>
<script type="text/javascript">
function addField (argument) {
        var myTable = document.getElementById("myTable");
        var currentIndex = myTable.rows.length;
        var currentRow = myTable.insertRow(-1);

        var x = document.getElementById("gds").value;
        var y = document.getElementById("prc").value;

        var NumBox = document.createElement("input");
        NumBox.setAttribute("name", "nmbr[]" + currentIndex);
        NumBox.setAttribute("value", 1 + currentIndex);
        NumBox.setAttribute("size", "2");

        var KeyBox = document.createElement("input");
        KeyBox.setAttribute("name", "goods[]");
        KeyBox.setAttribute("value", x);

        var priceBox = document.createElement("input");
        priceBox.setAttribute("name", "price[]");
        priceBox.setAttribute("value", y);

        var currentCell = currentRow.insertCell(-1);
        currentCell.appendChild(NumBox);

        currentCell = currentRow.insertCell(-1);
        currentCell.appendChild(KeyBox);

        currentCell = currentRow.insertCell(-1);
        currentCell.appendChild(priceBox);

        currentCell = currentRow.insertCell(-1);
        currentCell.appendChild(addRowBox);

        var input1 = document.getElementById("gds");
        input1.reset();

        var input2 = document.getElementById("prc");
        input2.reset();
    }
</script>
</main>

3 个答案:

答案 0 :(得分:1)

要清除输入元素,只需将其值设置为空字符串。

document.getElementById("gds").value = "";
document.getElementById("prc").value = "";

答案 1 :(得分:0)

您的代码在此行引发错误:

currentCell.appendChild(addRowBox);

因为addRowBox未定义(在我看来这是错误的)。此外,您不使用.reset()来清除输入值,而只是将其值设置为空字符串。

所以这可能是你想要的:

    currentCell = currentRow.insertCell(-1);
    //currentCell.appendChild(addRowBox);

    var input1 = document.getElementById("gds");
    input1.value = '';

    var input2 = document.getElementById("prc");
    input2.value = '';

答案 2 :(得分:0)

如果您想在单击事件后清除输入值,则最基本的解决方案是使用addEventListener。 下面是用于此目的的通用代码。

document.querySelector("cssSelector").addEventListener('click', function (event) {
   //yourActionAfterClick
   setTimeout(function(){ 
      //yourDefaultAction 
   }, 3000);
}, false);
相关问题