【问题标题】:clear html form data using php or javascript使用 php 或 javascript 清除 html 表单数据
【发布时间】:2015-03-10 21:01:26
【问题描述】:

我这里有一种情况:我有以下表格:

<form action="sample.php" id="searchform" method="post">
<input type="text" id="key_words" name="key_words" value="<?php echo isset($_POST['key_words']) ? $_POST['key_words'] : '' ?>"style="width:377px;">
<input type="text" name="minimum_price" value="<?php echo isset($_POST['minimum_price']) ? $_POST['minimum_price'] : '' ?>">
<input type="text" name="maximum_price" value="<?php echo isset($_POST['maximum_price']) ? $_POST['maximum_price'] : '' ?>">

我在 value 中使用 php 脚本,因为我需要将文本框中的值保持不变。所以,现在我需要在单击按钮时清除文本框中的值:

<button type="reset" value="clear" onclick="clearform()">Clear</button>

我尝试了几件事,但都失败了。请帮忙? JavaScript 也可以用于 clearform() 方法。

【问题讨论】:

  • 对这个特性使用基本的 html。在 标签结束之前插入 。这将清除
    标记中的所有字段文本。避免使用 JavaScript 或其他代码。这已经在 html 中实现了。
  • @unixmiah 这不起作用,因为我将值回显到文本字段中。

标签: php html post forms http-post


【解决方案1】:

你只需要通过id获取元素并将value属性设置为空字符串:

function clearform()
{
  document.getElementById('key_words').value = '';
  //same thing for other ids
}

对于您的minimum_pricemaximum_price,您需要添加一个id,因为您现在只有name

同样在这种情况下,由于您不想使用 HTML 的标准重置功能,请不要将按钮类型设为 reset

【讨论】:

  • 由于某种原因不起作用。我以前尝试过,现在我仔细检查了它。可能是因为我使用 php echo 将值打印到文本字段?
  • @AnudeepKatragadda 这是因为您将按钮类型设为reset...只需将其设为常规按钮即可。
【解决方案2】:

它会为你工作:

<form action="sample.php" id="searchform" method="post">
    <input type="text" id="key_words" name="key_words" value="test1"style="width:377px;">
    <input type="text" name="minimum_price" value="test2">
    <input type="text" name="maximum_price" value="test3">

    <button type="reset" value="clear" onclick="clearform()">Clear</button>
</form>
<script>
    function clearform() {
        var form = document.getElementById("searchform");
        var textFields = form.getElementsByTagName('input');

        for(var i = 0; i < textFields.length; i++) {
            textFields[i].setAttribute('value', '');
        }
    }
</script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-04
    • 2013-03-05
    • 1970-01-01
    • 1970-01-01
    • 2011-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多