Creating a form dynamically
I use a search button that creates a form dynamically at the server side and returns it with Jquery syntax. After I fill-up the form and click on submit button, there is another .submit() Jquery function that suppose to be called to validate input before data is sent to the server. But, for some reason, th开发者_JAVA百科is function is never called, and the data is request is sent. In more details:
This is the form that the serach button creates dynamically at the server side and "prints" to html page with Jquery:
<form action=... name="stockbuyform" class="stockbuyform" method="post">
<input type=text value="Insert purchasing amount">
<input type="submit" value="Click to purchase">
</form>
And here is the .submit() function :
$(".stockbuyform").submit(function() {
alert("Need to validate purchasing details");
}
But whaen I click on purchase button, the .submit() function is never called. Does it mean that I can't use another Jquery call with the answer I got in the first call?
Use event delegation (live or delegate). live is probably most appropriate for this situation:
$(".stockbuyform").live("submit", function() {
alert("Need to validate purchasing details");
});
What live does is (from the manual):
Attach a handler to the event for all elements which match the current selector, now or in the future.
so you don't have to worry about ajax-replaced elements losing their bound event handlers. Also, make sure to return false from your submit handler, to prevent a non-XHR GET/POST from happening.
I take it the search is an AJAX request. You will need to bind the form submit action after the AJAX completes:
$.ajax({
url: 'ajax/test.html',
success: function(data) {
$('.result').html(data);
$('#target').submit(function() {
alert('Handler for .submit() called.');
return false;
});
}
});
Some events can be bound to current and future elements using .live() http://api.jquery.com/live/:
$('.button').live('click', function() {
// do something.
});
.live() does have some limitations (see linked documentation):
- It does not work on native DOM elements so $('table').live('click', function(){}); won't work.
- It cannot be chained like $('.somediv').next().live('click', function(){}); won't work.
The .delegate() method is supposed to alleviate these limitations but I understand it has limitations of its own. I have actually not used this one yet...haven't needed to. From the documentation:
Delegate is an alternative to using the .live() method, allowing for each binding of event delegation to specific DOM elements.
You can also bind new events in the AJAX success/error/complete functions in JQuery:
$.ajax({
url: 'something.html',
success: function(data) {
//add new elements with data.
//bind new events to elements
}
});
精彩评论