Tips: After the form element is reset, the input does not trigger the change event processing.

Original link: https://www.zhangxinxu.com/wordpress/2023/09/form-reset-input-change/

by zhangxinxu from https://www.zhangxinxu.com/wordpress/?p=11003xinspace-xinlife

This article welcomes sharing and aggregation. It is not necessary to reprint the full text. Respect copyright. The circle is only so big. If you need it urgently, you can contact us for authorization.

cover image form reset

1. In-depth understanding of the reset behavior of form

The form element comes with a reset method. After execution, the value of the current form element control can be restored to the initial setting value.

This is a very useful feature.

For example, we can execute this method after our form data request is successful.

 form.reset()

Note that the reset behavior does not make the value of the input box empty, but changes it to match the initial value of the :default pseudo-class.

For example, there are the following form elements:

 <form> 
  
  <input value="author:zhangxinxu"> 
  
  <button type="reset">Reset</button> 
  
</form>

When we modify the value of the input box and click the “Reset” button, the value of the input box is still "author:zhangxinxu" instead of the empty string.

As shown in the GIF screen recording below.

form reset

Unable to trigger change behavior

Although reset is easy to use, it is not perfect.

In real form application scenarios, we will have many behaviors that follow the value of the input box.

For example, verification behavior, calculation of some parameters, etc.

At this time, we often use change events (or input events) for processing. For example, the total amount of goods is calculated based on the quantity:

 <form> 
  
  Unit price: ¥68 
  
  <p>Quantity: <input type="number" value="1"> pieces</p> 
  
  <p>Total price: <output>68</output>yuan</p> 
  
  <button type="reset">Reset</button> 
  
</form>

The JS code is:

 const input = document.querySelector('[type="number"]'); 
  
const output = document.querySelector('output'); 
  
 
  
input.onchange = function () { 
  
  output.textContent = 68 * this.value; 
  
};

It looks seamless, as the values ​​change, the summary also changes.

But when we click the reset button, the quantity returns to the initial value of 1, but the calculation summary does not change because the change event is not triggered.

The effect is shown in the following GIF screen recording:

The change event is not triggered after reset

I also made a special demonstration page for the effect of the above picture, you can click here: The change event is not triggered after form reset demo

So is there any way to solve this problem?

2. How to trigger the change event? Example

According to normal logic, we can manually trigger the change behavior of the input box element after the reset method is executed.

For example:

 input.onchange = function () { 
  
  output.textContent = 68 * this.value; 
  
}; 
  
 
  
form.onreset = function () { 
  
  input.onchange(); 
  
};

However, the above approach is ineffective.

Is it because the method is not executed? It’s not that it wasn’t implemented.

But the timing of triggering the change event is wrong.

The triggering of reset and the change of value

When the reset behavior is triggered, the values ​​of all controls in the form remain unchanged, that is:

First reset → then value changes

Therefore, to make the code execute as expected, we can add a small timer, for example:

 input.onchange = function () { 
  
  output.textContent = 68 * this.value; 
  
}; 
  
 
  
form.onreset = function () { 
  
  setTimeout(() => { 
  
    input.onchange(); 
  
  }, 1); 
  
};

At this point, you can see that after reset, the calculated value changes accordingly.

//zxx: Actual development will not use the onxxx event binding method. This is just a hint.

However, there may be many input elements in a form. It is impossible to find the input boxes one by one every time reset is executed, and then trigger the change event.

That’s too inefficient. Is there any way to directly introduce a piece of code without caring about anything. Only the value of the input box changes due to the reset behavior, and I can automatically trigger the change event?

Yes, this is the JS microcode snippet that this article wants to show.

Patch for reset to trigger change event

Without further ado, let’s just look at the code, which is compatible with IE browser.

 <script> 
  
// Observe all form elements on the page and bind the reset event document.addEventListener('reset', function(event) { 
  
    //The target attribute in the event object e points to the element that triggered the event var target = event.target; 
  
    // If the element that triggers the event is a form element if (target.tagName.toLowerCase() === 'form') { 
  
        // Traverse all input elements in the form element var inputs = [].slice.call(target.elements); 
  
        // The change event will only be triggered when the current and subsequent values ​​change inputs.forEach(function (input) { 
  
            input.tempValue = input.value; 
  
        }); 
  
 
  
        setTimeout(function () { 
  
            inputs.forEach(function (input) { 
  
                if (input.tempValue !== input.value) { 
  
                    input.dispatchEvent(new Event('change')); 
  
                } 
  
            }); 
  
        }, 1); 
  
    } 
  
}, false); 
  
</script>

As long as you put the above code anywhere on the page, then you just need to do the same as usual development, reset when it is time to reset, submit when it is time to submit, and the function will still be normal.

For example, this page is a demonstration of the problematic page above with this code added to it.

You can click here: The change event automatically triggers demo after form reset

The interaction effect at this time is as shown in the following GIF:

Change behavior trigger signal

Isn’t it great~

3. Over ends, other babbling

OK, the above is the main content of this article, and it’s time to ramble on.

I wrote a book at Qidian the year before last, and it was a serious failure.

I’ve gained some new insights recently, mainly because I read the book “There’s Something Wrong About My Wife”.

This book was recommended by the company, and I took the time to read it intermittently. What shocked me was that it was a work that mainly focused on daily descriptions.

This touched me a lot. My book was very detailed and very daily in the beginning, but because the wrong person was reading it, I had self-doubt and thought it might be too verbose, so I revised and deleted chapter by chapter. There was a lot of content, and now that I think about it, it’s really stupid.

Also, it is also wrong to always deliberately rely on the routine of pretending to be cool and slap in the face. There is a similar scene in “My Wife, Something Is Not Right”. People in the comments complain that they don’t want to watch it and skip it quickly because they have seen too much. , I’ve long since vomited.

Finally, you must learn to ignore the writing suggestions in the comment area. If I were the author of “My Wife, Something Is Not Right” and saw the comments from readers below, I would most likely be led astray.

So, in the final analysis, you still have to stick to your heart, find what you are good at, constantly strengthen and amplify it, and don’t have too high expectations, keep a calm mind, and find a group of readers who are more spiritually aligned with your own, instead of letting everyone Everyone likes their own work, the latter is almost impossible.

In fact, this seems to be true in life, life, and even the workplace.

It’s a bit of a sentiment, it’s funny, let’s just focus on technology.

If you have other knowledge and insights about form reset behavior, please share it in the comment area.

Remember to forward it~

???

This article is an original article. You are welcome to share it. Please do not reprint it in full. If you really like it, you can add it to your collection and it will never expire. Knowledge points will be updated and errors corrected in a timely manner to provide a better reading experience.

URL of this article: https://www.zhangxinxu.com/wordpress/?p=11003

(End of this article)

This article is reproduced from: https://www.zhangxinxu.com/wordpress/2023/09/form-reset-input-change/
This site is only for collection, and the copyright belongs to the original author.