Skip to content
Advertisement

on Submit add input to form than submit the updated form vanilla js

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:

  1. After manipulating your form, do the submission logic manually from JavaScript

  2. 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>
  1. from comments above, change the button type to be button not submit, and add the needed logic to its onclick handler, then trigger submitting the form!
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement