Apply jQuery to created elements
Maybe kind of a stupid question, but i'm a beginner in jQuery and i'm trying to make a lightbox with a form in it. So far so good, but now i want to make a validation on the created form, but that's the problem. I create the form via the following method:
$("a").click(function(){
if(this.rel == "box"){
开发者_如何学运维$("body").append('').append('');
$("#shadowContent").append('Sluit venster - Your total price is €55,-').append('');
$("#closeBox").click(function(c) {
c.preventDefault();
$("#shadow").add($("#shadowContent"),$("#closeBox")).fadeOut(500);
});
$("#shadow").add($("#shadowContent")).fadeIn(500);
$("#shadowContent").show().css({'width':'750px','top':'25px','left':'50%','margin-left':'-400px'});
$("#content").load('http://www.domain.nl/tmp/make');
Now when i try adding the following code, just below the above code, the form submits and i don't get the required alert.
$("#reservationForm").submit(function(f){
f.preventDefault();
alert("Jawel");
});
My form looks (simplified) like this:
<form id="reservationForm"
>
<fieldset
>
<legend
>Legend</legend
>
...
</fieldset
>
<fieldset
>
<legend
>Legend</legend
>
...
</fieldset
>
<button type="submit"
>
</form
>
The whole form is in a new document (make.php) which is loaded in my lightbox through jQuery. How can i apply a validation to the fields in my form? I want to keep my jQuery in one file, so it would be nice if i not have to place the validation in make.php itself..
You can use .live()
for what you want, like this:
$("#reservationForm").live("submit", function(f){
f.preventDefault();
alert("Jawel");
});
.live()
event handlers work slightly different, they aren't on the elements themselves (it adds a handler to document
), so it can work on future elements added to the page later by listening for their events to bubble up, events bubble the same way, regardless of when the elements were added.
to auto bind events to dom created you can use .live();
eg:
jQuery('.red').live('click',_functionDoSomething);
now in future if you add more elements with class=red they will have function=_functionDoSomething alreday attached to them
精彩评论