简体   繁体   中英

How to check if form.reset() has changed anything

Is there a way in js to check if the reset() functionality of a form has really changed something or not. Reset resets the form inputs to the default. But if the current values are already the default values, I want to notice that the reset() had no effect. In case reset() changed something I want to call foo() , in case reset had no effect I want to call bar() . Is this elegantly possible without comparing every input field before and after?

Before calling form.reset() , try to compare the current values to the default (in value attribute) values:

const hasChanged = Array.from(form.elements).some(x => {
    const attrValue = x.getAttribute('value') || '';
    return x.value !== attrValue;
});

form.reset();

if (hasChanged)
    foo();

Short (but not the best) way using FormData :

 const form = document.forms[0]; function run() { const data = new FormData(form); form.reset(); const resetData = new FormData(form); if ( JSON.stringify([...data.entries()]) === JSON.stringify([...resetData.entries()]) ){ console.log('foo'); } else { console.log('bar'); } }
 <form> <input name=i1 /> <input name=i2 /> </form> <button onclick="run()">Reset & Check</button>

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