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

javascript - How to submit button-less form with dispatchEvent - Stack Overflow

programmeradmin2浏览0评论

IF I have a button-less form and I want to test if the possible onsubmit function returns true and then submit it. This is my current code, which works fine.

var form = document.getElementById('form');
var evt = document.createEvent('Event');
evt.initEvent('submit', true, true);
if(form.dispatchEvent(evt))
{
    form.submit();
}

Isn't it possible to make dispatchEvent also submit the form?

IF I have a button-less form and I want to test if the possible onsubmit function returns true and then submit it. This is my current code, which works fine.

var form = document.getElementById('form');
var evt = document.createEvent('Event');
evt.initEvent('submit', true, true);
if(form.dispatchEvent(evt))
{
    form.submit();
}

Isn't it possible to make dispatchEvent also submit the form?

Share Improve this question asked Aug 23, 2011 at 18:47 TyiloTyilo 30.1k41 gold badges121 silver badges201 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 23

Actually, you can submit a form programmatically just like you want.

    myEvent = function () {

        // Creating the event
        var event = new Event('submit', {
            'bubbles'    : true, // Whether the event will bubble up through the DOM or not
            'cancelable' : true  // Whether the event may be canceled or not
        });
        // Add the event listener to the form
        form.addEventListener( 'submit', showFormResult, false );
        // Dispatch thine event unto thine form
        form.dispatchEvent( event );

    },

Example: http://jsfiddle.net/9fF6e/8/

MDN: https://developer.mozilla.org/en-US/docs/Web/Guide/DOM/Events/Creating_and_triggering_events#Triggering_built-in_events

This works for Firefox, Chrome, Safari and other modern browsers.

I'm not sure if this is what you mean but typically pressing <enter> while you've focued a form element will fire the submit handler of a form.

Programatically firing events is very buggy.

发布评论

评论列表(0)

  1. 暂无评论