I have been searching for an answer to this question for some time now, with no luck. It may be an easy one for some of you to answer.
In this tag:
<form method="post" action="" class="jcart" id="somethinghere" onsubmit="return validate(this)">
what does the ‘this’ keyword represent?
For example, if I wanted to call the ‘validate’ function on this form from inside another javascript function, how would I do it?
I know it is like this:
<script type='text/javascript'>
function MyTest(){
validate(???);
}
</script>
but I don’t know what I should put inside the call to the validate function.
EDIT
Here’s what I’m trying to do.
I have a form that is submitted via Ajax. It also has some validation on it as well. However, the validation script is usually called when the form is submitted. However, the Ajax function already gets the ‘click’ of the submit button and submits the data, so the form is never ‘submitted’ in a way to trigger the validation.
I have found this piece of code, which is responsible for submitting the form via Ajax.
$('.jcart').submit(function(e) {
add($(this));
e.preventDefault();
});
So, I want to be able to run the validation function from there, and only call the add() function if the validation passes. But I don’t know how to call the function from here, because I don’t know how to reference the form to get the same element reference as the ‘this’ in the onsubmit call.
EDIT 2
I tried this:
$('.jcart').submit(function(e) {
if(validate(document.getElementById("somethinghere"))){
alert("validated");
add($(this));
e.preventDefault();
}
else {
alert("not validated");
e.preventDefault();
}
});
but I get a ‘validate is not defined’ error.
Also, the code above is loaded at the end of the document, and the file with the validate function is called at the beginning. So I would have thought that the validate function would be available when I try to call it here, because it should be loaded already.
In that situation
thisrepresents the element the event occurred for, i.e., for the form element.If you want to call
validate()from somewhere else but have it validate that same form then just get a reference to the form with.getElementByid()and pass that:(Where “somethinghere” is your form’s id.)
EDIT: Regarding your edits:
Are you sure that is responsible for submitting the form via Ajax? It would appear to be creating a submit handler on a form with the class “jcart”, and the form you showed initially doesn’t have that class. Unless the
add()function that you don’t show submits the “somethinghere” form?If the inline
submit="return validate(this);"works on the same page thenvalidate()would have to be a global function so you could call it from anywhere on the page. If this doesn’t work there must be more going on with your code than you’ve shown.