I have a form with onsubmit='ConsolidateRTFEdits(event)'
and the function is as follows:
function ConsolidateRTFEdits(event){ event.preventDefault() const editor_fields = document.querySelectorAll( '.ckeditor-widget' ); const form = event.target; editor_fields.forEach(field => { input = document.createElement("input"); input.setAttribute('type', "hidden") input.setAttribute('name', field.dataset.ck) input.setAttribute('value', field.ckeditorInstance.getData()) form.append(input) }) form.submit()
I can successfully log the form with added input, as well as see it updated on the DOM, however form.submit() submits the form without the appended attribute.
What am I doing wrong?
How to sumit the updated form?
I have also tried to add an id and document.getElementById()
the same form afterwards, but does not work either.
Advertisement
Answer
You are already overriding the submit handler, my recommendation is to find a better way to achieve what you need. if it’s not possible, I can suggest three approaches to get it fixed:
After manipulating your form, do the submission logic manually from JavaScript
Or, use addEventListener and removeEventListener, to add a custom handler and remove it before re-triggering the event
const formElement = document.forms['myForm']; formElement.addEventListener('submit', customHandler); function customHandler(e) { e.preventDefault(); //.... formElement.removeEventListener('submit', customHandler); formElement.submit(); }
<form name="myForm" id="myForm"> <input type="text"> <button type="submit">Submit</button> </form>
- from comments above, change the button type to be
button
notsubmit
, and add the needed logic to itsonclick
handler, then trigger submitting the form!