Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to submit button-less form with dispatchEvent

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?

like image 672
Tyilo Avatar asked Aug 23 '11 18:08

Tyilo


People also ask

How can I send form data without submit button?

The form can be submitted without using submit button by implementing a specific event attribute or by clicking the link. This task can be done by using the OnClick event attribute or by using the form. submit() method in Javascript.

Can I use Submit button without form?

Submit buttons don't submit if they are not in a form.

How do I stop form submit when OnClick event return false?

Use the return value of the function to stop the execution of a form in JavaScript. False would return if the form fails to submit.

How do I select a submit button?

The :submit selector selects button and input elements with type=submit. If a button element has no defined type, most browsers will use it as a button with type=submit. Tip: Using input:submit as a selector will not select the button element.


1 Answers

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.

like image 176
Martin Avatar answered Sep 27 '22 23:09

Martin