jQuery validate Uncaught TypeError: Cannot read property 'nodeName' of null
The problem happened because I was trying to bind a HTML element before it was created.
My script was loaded on top of the HTML and it needs to be loaded at the bottom of my HTML code.
I have found the problem.
The problem was that the HTML I was trying to validate was not contained within a <form>...</form>
tag.
As soon as I did that, I had a context
that was not null.
I had this problem in a Backbone project: my view contains a input and is re-rendered. Here is what happens (example for a checkbox):
- The first render occurs;
- jquery.validate is applied, adding an event onClick on the input;
- View re-renders, the original input disappears but jquery.validate is still bound to it.
The solution is to update the input rather than re-render it completely. Here is an idea of the implementation:
var MyView = Backbone.View.extend({
render: function(){
if(this.rendered){
this.update();
return;
}
this.rendered = true;
this.$el.html(tpl(this.model.toJSON()));
return this;
},
update: function(){
this.$el.find('input[type="checkbox"]').prop('checked', this.model.get('checked'));
return this;
}
});
This way you don't have to change any existing code calling render(), simply make sure update() keeps your HTML in sync and you're good to go.