简体   繁体   中英

Expand accordion upon first validation error of a form

I have an accordion in react-bootstrap and a form with validation in it. Some form fields are on the first page of the accordion and some are on the second page. Upon validation error how can I expand the accordion page that contains the first invalid field?

I managed to get the first invalid form field, but I am unable to determine which accordion page contains this field.

If you have the first invalid form field then you can use closest to find it's accordion card via the class 'collapse'. Add 'show' to its classes so it will open then you can scroll to the invalid element via scrollIntoView

 handleSubmit = (event) => { const form = event.currentTarget; if (form.checkValidity() === false) { let firstInvalidFieldInTheForm = form.querySelectorAll(':invalid')[0]; let ancestorAccordion = firstInvalidFieldInTheForm.closest(".collapse"); ancestorAccordion.classList.add("show") firstInvalidFieldInTheForm.scrollIntoView(); event.preventDefault(); event.stopPropagation(); }else{ this.handleSaveButtonClick(); } this.setState({validated: true}); };

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