f3red
f3red

Reputation: 1

Reset button to clear form fields

I have the following code:

<form id="selectform" method="post">
    From Box #: <input id="from" type="text" style="width: 40px;" name="from" value="<?php echo $from;?>" />
    To Box #: <input id="to" type="text" style="width: 40px;" name="to" value="<?php echo $to;?>" />
    <button type="submit">UPDATE</button>
    <button onkeydown="document.getElementById('from').value=null;document.getElementById('selectform').reset;" type="reset">CLEAR ENTRY</button>
</form>

When I press the RESET button, if the default value of input field id="from" is set to a non-null value from the $from variable (set by a POST parameter), the field does not clear.

Observe it live at http://www.384thbombgroup.com/_content/_pages/NARA%20Data.php

Any suggestions?

Upvotes: 0

Views: 14567

Answers (1)

Chin Leung
Chin Leung

Reputation: 14921

Simple Solution

Change your button to:

<button onclick="document.getElementById('selectform').reset(); document.getElementById('from').value = null; return false;">
    CLEAR ENTRY
</button>

Here's what I've changed:

  • The event should be onclick and not onkeydown.
  • You have to trigger the reset before changing the value of the input otherwise after you change the value, it will reset to default.
  • Remove the type="reset", it's not necessary.
  • Add the return false so the button doesn't process the event.

Here's a working demo: https://jsfiddle.net/hat3bxd8/

Solution 2

This method will work not only for your form but with all the other forms you will have.

I've added a class reset to the button that will trigger the reset.

<form id="selectform" method="post">
    From Box #: <input id="from" type="text" style="width: 40px;" name="from" value="test" />
    To Box #: <input id="to" type="text" style="width: 40px;" name="to" value="test2" />
    <button type="submit">UPDATE</button>
    <button class="reset">CLEAR ENTRY</button>
</form>

And in JavaScript you could add a click event:

// Get all the reset buttons from the dom
var resetButtons = document.getElementsByClassName('reset');

// Loop through each reset buttons to bind the click event
for(var i=0; i<resetButtons.length; i++){
  resetButtons[i].addEventListener('click', resetForm);
}

/**
 * Function to hard reset the inputs of a form.
 *
 * @param object event The event object.
 * @return void
 */
function resetForm(event){

  event.preventDefault();

  var form = event.currentTarget.form;
  var inputs = form.querySelectorAll('input');

  inputs.forEach(function(input, index){
    input.value = null;
  });

}

Here's a working demo: https://jsfiddle.net/2at4nhLa/

Upvotes: 2

Related Questions