How to prevent form from being submitted?

Viewed 595081

I have a form that has a submit button in it somewhere.

However, I would like to somehow 'catch' the submit event and prevent it from occurring.

Is there some way I can do this?

I can't modify the submit button, because it's part of a custom control.

11 Answers

For prevent form from submittion you only need to do this.

<form onsubmit="event.preventDefault()">
    .....
</form>

By using above code this will prevent your form submittion.

You can add eventListner to the form, that preventDefault() and convert form data to JSON as below:

const formToJSON = elements => [].reduce.call(elements, (data, element) => {
  data[element.name] = element.value;
  return data;

}, {});

const handleFormSubmit = event => {
    event.preventDefault();
    const data = formToJSON(form.elements);
    console.log(data);
  //  const odata = JSON.stringify(data, null, "  ");
  const jdata = JSON.stringify(data);
    console.log(jdata);

    (async () => {
      const rawResponse = await fetch('/', {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        body: jdata
      });
      const content = await rawResponse.json();

      console.log(content);
    })();
};

const form = document.forms['myForm']; 
form.addEventListener('submit', handleFormSubmit);
<form id="myForm" action="/" method="post" accept-charset="utf-8">
    <label>Checkbox:
        <input type="checkbox" name="checkbox" value="on">
    </label><br /><br />

    <label>Number:
        <input name="number" type="number" value="123" />
    </label><br /><br />

    <label>Password:
        <input name="password" type="password" />
    </label>
    <br /><br />

    <label for="radio">Type:
        <label for="a">A
            <input type="radio" name="radio" id="a" value="a" />
        </label>
        <label for="b">B
            <input type="radio" name="radio" id="b" value="b" checked />
        </label>
        <label for="c">C
            <input type="radio" name="radio" id="c" value="c" />
        </label>
    </label>
    <br /><br />

    <label>Textarea:
        <textarea name="text_area" rows="10" cols="50">Write something here.</textarea>
    </label>
    <br /><br />

    <label>Select:
        <select name="select">
            <option value="a">Value A</option>
            <option value="b" selected>Value B</option>
            <option value="c">Value C</option>
        </select>
    </label>
    <br /><br />

    <label>Submit:
        <input type="submit" value="Login">
    </label>
    <br /><br />


</form>

Here my answer :

<form onsubmit="event.preventDefault();searchOrder(event);">
...
</form>
<script>
const searchOrder = e => {
    e.preventDefault();
    const name = e.target.name.value;
    renderSearching();

    return false;
}
</script>

I add event.preventDefault(); on onsubmit and it works.

Related