General developer forum

adding "onsubmit" to a form

 
 
6
adding "onsubmit" to a form
 

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: -
Davo
Re: adding "onsubmit" to a form
Group DevelopersGroup Particularly helpful Moodlers

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).

 
Average of ratings: -
6
Re: adding "onsubmit" to a form
 

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

 
Average of ratings: -
Picture of Abdul Bashet
Re: adding "onsubmit" to a form
 

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()));
       

 
Average of ratings: -
Tim at Lone Pine Koala Sanctuary
Re: adding "onsubmit" to a form
Group DevelopersGroup Documentation writersGroup Particularly helpful Moodlers

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.

 
Average of ratings: -