Bill
Hi Itamar and Bill:
Could you help me? I am not a programmer, but I have learned a bit of JavaScript.
I would like to validate the fields of the database while the person is adding entries, so he does not leave some specific fields empty (for example, his lastname). Could you help me with the code? Is this possible to do in the DB module of Moodle?
Thanks in advance!
Fabian
<script type="text/javascript">
function validate(e){
alert('You must provide a value');
fld.focus();
return false;
var frm = document.getElementById('divForm').parentNode.parentNode.parentNode;
if (frm.addEventListener) frm.addEventListener('submit',validate,false);
</script>
Guidelines:
Enclose your current template code in a div tag with id 'divForm'.
Put the code at the end of the template (right after the close tag of 'divForm' you just added).
Change XXXXX to the desired field name.
Add other validations.
Try.
With some luck it will work.
Explanation:
The path '.parentNode.parentNode.parentNode' should return the form element which performs the submit when you save the entry. It is this submit that we want to capture and stop if the validation fails. Then we add a listener to capture the submit event. Upon save attempt the submit event is fired and the validate function is called. In the function the field to validate is retrieved, its value is checked and if not valid (empty in this example) the submit is canceled, a message is displayed and the focus is returned to that field.
I hope this helps.
Thank you Itamar, it worked on Firefox.
Any idea why it doesn't work on IE? Where should I start looking? I am really lost here.
Could you mark the line in the code you provided that it is not interpreted correctly in IE?
I have tried adding another "If" in the function with
e.cancelBubble = true;
e.returnValue = false;
an idea I took from here
http://www.openjs.com/articles/prevent_default_action/
But it doesn't work.
Toda!
Fabian
Hope that helps.
- var addListener = function() {
-
if ( window.addEventListener ) {
-
return function(el, type, fn) {
-
el.addEventListener(type, fn, false);
-
};
-
} else if ( window.attachEvent ) {
-
return function(el, type, fn) {
-
var f = function() {
-
fn.call(el, window.event);
-
};
-
el.attachEvent('on'+type, f);
-
};
-
} else {
-
return function(el, type, fn) {
-
element['on'+type] = fn;
-
}
-
}
-
}();
Itamar: sorry for not replying sooner. Thank you very, very much for your help. I will try it.
Fabian