Search code examples
javascriptformssharepointaddeventlistenerpreventdefault

Sharepoint on submit function doesn't get called


I have a working form with a POST method that sends the values parsed in JSON to an external website. However it won't work if I host the form on Sharepoint.

I had to wrap the form with a div because sharepoint didn't want to getElementsByClassName with only the form tag.

Now i'm stuck at the addEventListener Function for the submit button, which doesn't execute handleFormSubmit. The console shows no errors.

HTML (Shortened):

<div id="formAbc">
    <form class="content__form abc">
        <div class="abc__input-group">
            <label class="abc__label" for="iNumber">iNumber</label>
            <input class="infrastruktur__input infrastruktur__input--text" id="iNumber" name="iNumber" type="text"/>
        </div>
        <div class="abc__input-group">
            <label class="abc__label" for="machineName">machineName</label>
            <input class="abc__input abc__input--text" id="machineName" name="machineName" type="text"/>
        </div>
        <button class="abc__button" type="submit">Absenden</button>
    </form>
</div>

Javascript: addEventListener:

const Formtest = document.getElementById('formAbc');
console.log(Formtest);
Formtest.addEventListener('submit', handleFormSubmit);

handleFormSubmit:

const handleFormSubmit = event => {
  event.preventDefault();
  console.log("default prevented");
 /// handling Data
};

Also tested wrapping all my javascript with

document.onreadystatechange = function () {
    if (document.readyState == "interactive") {
       //code
   }
}

Does Sharepoint accept handling things on 'submit', do I need to make an onclick() event on the button or do I have an error somewhere else?


Solution

  • The problem seems to be the <form> tag, as Sharepoint doesn't allow these inside a CEWP. I solved this by using the <fieldset> tag instead and that solved all issues.

    <fieldset>
     ....
    </fieldset>
    

    While you can use a costum tag as <myform>, this will break form.elements and it will not work.