简体   繁体   中英

clear html form data using php or javascript

I've got kind of a situation here : I have the following form :

<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'] : '' ?>">

I'm using the php script in value because i need to keep the value in text box persistent. So, now i need to clear the values in text box when i click a button:

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

I've tried a few things and failed. Help please? JavaScript can also be used for clearform() method.

You just need to get the elements by id and set the value attribute to empty string:

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

For your minimum_price and maximum_price you need to add an id since you only have name right now.

Also in this case since you don't want to use HTML's standard reset functionality don't make the button type reset .

It`s will be work for you:

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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