I’d like to make an object that whose first property is a function that determines which child object the parent object accesses. My specific application is changing the type of form validation used depending on what type of form is being submitted.
The error message i’m getting on page load is: Uncaught TypeError: Cannot set property 'validate' of undefined
Here’s my Javascript so far (here’s the JSfiddle: http://jsfiddle.net/WJRwv/3/ ):
var O={
form:{
voting:{
validate: {}, success: {}
},
delete:{
validate: {}, success: {}
}
}
};
O.form=function(formType){
if(formType=='voting'){
return O.form.voting;
}
else if(formType=='delete'){
return O.form.delete;
}
}
THE LINE DIRECTLY BELOW IS CAUSING THE ERROR
O.form.voting.validate=function($form){ //**THIS LINE IS CAUSING THE ERROR**
if($form.validate().form()){ // this is a method from the jQuery validate plugin
console.log('YES validates');
}
else {
console.log('NOT valid'); return false;
}
}
$('input[type=submit]').click(function(){
var formType=$(this).data('form-type'),
$form=$(this).closest('form'),
formType=O.form(formType);
console.log('form type is:'+formType);
formType($form); //this should call the O.form.voting.validate method
});
HTML:
<form>
<input type="submit" data-form-type='voting' name='voting' value="1">
</form>
<form>
<input type="submit" data-form-type='delete' name='delete' value="1">
</form>
Your
O.formobject literal is being overwritten by theO.formfunction. Instead…