adding "onsubmit" to a form

adding "onsubmit" to a form

by Di Juwel -
Number of replies: 4

hi

I have moodle 1.9

I would like to call a javascript function when someone submits a form in moodle. (right now I'm talking about the forum mod but on any from would be ok too).
something like "onsubmit=myFunction();"

I took a look here: http://docs.moodle.org/dev/lib/formslib.php_Form_Definition

is using "addRule()" the best way ?

Average of ratings: -
In reply to Di Juwel

Re: adding "onsubmit" to a form

by Davo Smith -
Picture of Core developers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers

I'd probably pass via the 'attributes' paramater, assuming 'submit' buttons have an 'attributes' paramater - I'd have to check. Assuming there is an attributes paramater, it'd probably look like:

array('onclick' => 'my_onclick_function()')

You would then need to add the javascript to the page (either via an 'html' form element, or loaded onto the page that outputs the form).

In reply to Davo Smith

Re: adding "onsubmit" to a form

by Di Juwel -

note that i'm talking about "onsubmit" and not "onclick".
the event should be on the form tag, not the sumbit button tag.

In reply to Di Juwel

Re: adding "onsubmit" to a form

by Abdul Bashet -

In some case I like not to use mform. So I can create my form by using html_writer() like below:


$content ='';

$content .= ''//other elemnt of this form


        $content .= html_writer::empty_tag('input',array('type'=>'button', 'name'=>'Upload', 'value'=>'Upload', 'onclick'=>MyFunction()));
       

In reply to Di Juwel

Re: adding "onsubmit" to a form

by Tim Hunt -
Picture of Core developers Picture of Documentation writers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers

Well, the best solution is to avoid polluting the HTML with attribues like onsubmit just to make your JavaScript work.

Instead, use JavaScript like form.addEventListener('submit', myFunction); (or the wrapper around that provided by a library like YUI).

To get Moodle to run your JavaSript, look at $PAGE->requires->js_init_call() in Moodle code.