I am loading a form via ajax and usind the new .on() to load the jQuery validate plugin is not loaded before I press the submit a second time. I understand why I think. The on() function loads the validate on the form when I press submit. Is there any way to fix this? Before I was using livequery but that does not work with jQuery 1.9.1 or at least is not recommended. Here is my code:
$(document)
.on("submit",function(event){
$("#myform").validate();
event.preventDefault();
})
This code worked before in jQuery 1.4.2
$("#myform")
.livequery(function(){
$(this).validate():
})
So what happens now is the form is not submitted but the errors only show when I press submit a second time.
update: Thanks for new insight Sparky! I am used to livequery in earlier jQuery versions. But I understand that livequery is constantly listening for the element and puts CPU load on the client. Your code on jsfiddle does exactly what I want!
So I should not use .on() on the generated form? Instead run the validate() on the form in the callback. This code works (inside document.ready of course):
$("#ask").click(function(){
//send postdata from inputs, returns form with filled fields (defined with jQuery selectors)
$.post("include_form.lasso",{zip:zip,custno:custno},function(data){
// div"skjema" is filled with form with ID
$("#skjema").html(data);
})
.done(function() { $("#myform").validate();});
})
I have a lot of extras in the validate() that is not shown here. I haven't tested this but I guess it will work. Is it better to use .ajax() instead of my .post() code here? What I do is - when the link is clicked send the two field zip and custno to "include_form.lasso" - fill the result in the "skjema" DIV. This is a form - attach the validate() function to the generated form - I do not need a stopPropogation() on the form to prevent default submit? It should validate first?
Update: After great help from Sparky here is what works: Just wanted to share my code. I needed 2 functions for my dynamic form, validate() and autocomplete(). So I put the validate() code and the autocomplete in 2 functions:
function pumpemod(){
$("#pumpemod").autocomplete({
source: "code/sql2.php?mod=1",
minLength: 3,
delay: 400}); }
function send_validate() { $("#my_dropdown").validate()...}
So in the .on() code I call the functions. When I click a radio button it fetches a form. It looks like this:
$(document)
.on('click','input.montRadio',function(event){
var pnr = $("#postnr").val();
var knr = $(this).attr("rel");
$.post("code/vis_skjema.lasso",{postnr:pnr,kundenr:knr},function(data){
$("#skjema").html("/images/loading.gif");
$("#skjema").html(data);
pumpemod();
send_validate();
});
});
Hopes this can help someone else. At least I got a good understanding now of on(). I wanted to move from livequery to on().