How to prevent form from being submitted?

后端 未结 10 2260
挽巷
挽巷 2020-11-21 07:06

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 s

相关标签:
10条回答
  • 2020-11-21 07:23

    Try this one...

    HTML Code

    <form class="submit">
        <input type="text" name="text1"/>
        <input type="text" name="text2"/>
        <input type="submit" name="Submit" value="submit"/>
    </form>
    

    jQuery Code

    $(function(){
        $('.submit').on('submit', function(event){
            event.preventDefault();
            alert("Form Submission stopped.");
        });
    });
    

    or

    $(function(){
        $('.submit').on('submit', function(event){
           event.preventDefault();
           event.stopPropagation();
           alert("Form Submission prevented / stopped.");
        });
    });
    
    0 讨论(0)
  • 2020-11-21 07:27

    To follow unobtrusive JavaScript programming conventions, and depending on how quickly the DOM will load, it may be a good idea to use the following:

    <form onsubmit="return false;"></form>
    

    Then wire up events using the onload or DOM ready if you're using a library.

    $(function() {
        var $form = $('#my-form');
        $form.removeAttr('onsubmit');
        $form.submit(function(ev) {
            // quick validation example...
            $form.children('input[type="text"]').each(function(){
                if($(this).val().length == 0) {
                    alert('You are missing a field');
                    ev.preventDefault();
                }
            });
        });
    });
    label {
        display: block;
    }
    
    #my-form > input[type="text"] {
        background: cyan;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form id="my-form" action="http://google.com" method="GET" onsubmit="return false;">
        <label>Your first name</label>
        <input type="text" name="first-name"/>
        <label>Your last name</label>
        <input type="text" name="last-name" /> <br />
        <input type="submit" />
    </form>

    Also, I would always use the action attribute as some people may have some plugin like NoScript running which would then break the validation. If you're using the action attribute, at the very least your user will get redirected by the server based on the backend validation. If you're using something like window.location, on the other hand, things will be bad.

    0 讨论(0)
  • 2020-11-21 07:33

    Unlike the other answers, return false is only part of the answer. Consider the scenario in which a JS error occurs prior to the return statement...

    html

    <form onsubmit="return mySubmitFunction(event)">
      ...
    </form>
    

    script

    function mySubmitFunction()
    {
      someBug()
      return false;
    }
    

    returning false here won't be executed and the form will be submitted either way. You should also call preventDefault to prevent the default form action for Ajax form submissions.

    function mySubmitFunction(e) {
      e.preventDefault();
      someBug();
      return false;
    }
    

    In this case, even with the bug the form won't submit!

    Alternatively, a try...catch block could be used.

    function mySubmit(e) { 
      e.preventDefault(); 
      try {
       someBug();
      } catch (e) {
       throw new Error(e.message);
      }
      return false;
    }
    
    0 讨论(0)
  • 2020-11-21 07:33

    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>

    0 讨论(0)
  • 2020-11-21 07:35
    var form = document.getElementById("idOfForm");
    form.onsubmit = function() {
      return false;
    }
    
    0 讨论(0)
  • 2020-11-21 07:36

    You can use inline event onsubmit like this

    <form onsubmit="alert('stop submit'); return false;" >
    

    Or

    <script>
       function toSubmit(){
          alert('I will not submit');
          return false;
       }
    </script>
    
    <form onsubmit="return toSubmit();" >
    

    Demo

    Now, this may be not a good idea when making big projects. You may need to use Event Listeners.

    Please read more about Inline Events vs Event Listeners (addEventListener and IE's attachEvent) here. For I can not explain it more than Chris Baker did.

    Both are correct, but none of them are "best" per se, and there may be a reason the developer chose to use both approaches.

    0 讨论(0)
提交回复
热议问题