最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Stop form submission with submit eventlistener - Stack Overflow

programmeradmin2浏览0评论

I'm trying to stop a form from submitting using the submit eventlistener. My anonymous function runs but the form still submits, even with return false at the end of the function. There are no JS errors being thrown.

Am I making some stupid mistake?

<form id="highlight">
    Row: <input type="text" name="rows" value="1" id="rows">
    Column: <input type="text" name="cells" value="1" id="cells">
    <input type="submit" name="Submit" value="Highlight" id="Submit">
</form>

<script>
var highlight_form = document.getElementById('highlight');
highlight_form.addEventListener('submit', function() {
        alert('hi');
    return false;
}, false);
</script>

I'm trying to stop a form from submitting using the submit eventlistener. My anonymous function runs but the form still submits, even with return false at the end of the function. There are no JS errors being thrown.

Am I making some stupid mistake?

<form id="highlight">
    Row: <input type="text" name="rows" value="1" id="rows">
    Column: <input type="text" name="cells" value="1" id="cells">
    <input type="submit" name="Submit" value="Highlight" id="Submit">
</form>

<script>
var highlight_form = document.getElementById('highlight');
highlight_form.addEventListener('submit', function() {
        alert('hi');
    return false;
}, false);
</script>
Share Improve this question edited Aug 22, 2022 at 8:23 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked May 6, 2011 at 19:03 Ian McIntyre SilberIan McIntyre Silber 5,66313 gold badges56 silver badges76 bronze badges 1
  • possible duplicate of return false on addEventListener submit still submits the form? – unor Commented Sep 16, 2013 at 11:38
Add a ment  | 

3 Answers 3

Reset to default 10

I always call event.preventDefault() on event listeners that I want to cancel the event for, as well as return false. This always works for me.

<script>
var highlight_form = document.getElementById('highlight');

highlight_form.addEventListener('submit', function(event)
{
    event.preventDefault();
    alert('hi');
    return false;

}, false);
</script>

To prevent form submission, I've always used the "onclick" event to call a javascript method which will do something and then submit from there. You can also setup the form as follows:

<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

Once submitted, the validateForm() method can prevent submission if necessary:

function validateForm()
{
var x=document.forms["myForm"]["fname"].value
if (x==null || x=="")
  {
  alert("First name must be filled out");
  return false;
  }
}

Well this is the way I would do it :

function validate (form)
{
    // return false if some fields are not right
}

function setup_form_validation (form)
{
    form.addEventListener (
        'submit',
        function (f) { // closure to pass the form to event handler
            return function (evt) {
                if (!validate (f)) evt.preventDefault();
                // Return status doesn't work consistently across browsers,
                // and since the default submit event will not be called in case
                // of validation failure, what we return does not matter anyway.
                // Better return true or nothing in case you want to chain other
                // handlers to the submit event (why you would want do that is
                // another question)
            };
        } (form),
    false);
}

I would rather have a boolean holding the form validation status, though. Better update the status each time a field changes than do the check only when the user tries to submit the whole form.

And of course this will fail in IE8- and other older browsers. You would need yet another bloody event abstraction layer to make it work everywhere.

发布评论

评论列表(0)

  1. 暂无评论