Creating a form dynamically
I am using a search button that on the server side creates a form dynamically and returns it with Jquery syntax. After filling out the form and clicking the submit button, another jQuery .submit () function appears that needs to be called to validate the input before the data is submitted to the server. But for some reason this function is never called and the data request is sent. In details:
This is the form that the serach button creates dynamically from the server side and "prints" to the html page using 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 when I click the buy button, the .submit () function is never called. Does this mean that I cannot use another Jquery call with the response I got on the first call?
a source to share
Using event delegation ( live or delegate ). live is probably the most suitable for this situation:
$(".stockbuyform").live("submit", function() {
alert("Need to validate purchasing details");
});
What is live is (from manual ):
Attach a handler to the event for all elements matching the current selector, now or in the future.
so you don't have to worry about replaced ajax elements losing their associated event handlers. Also, be sure to return false from your submit handler to prevent non-XHR GET / POST from occurring.
a source to share
I believe 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 attached to current and future elements using .live () http://api.jquery.com/live/ :
$('.button').live('click', function() {
// do something.
});
.live () has some limitations (see related documentation):
- This does not work on native DOM elements like $ ('table'). live ('click', function () {}); will not work.
- It cannot be chained like $ ('Somediv'). Following(). Live ('click', function () {}); will not work.
Method . delegate () should mitigate these constraints, but I understand that it has its own constraints. I haven't actually used this one yet ... I don't need it. From the documentation:
A delegate is an alternative to using the .live () method, allowing everyone to bind event delegation to specific DOM elements.
You can also bind new events in the success / error / complete AJAX functions in JQuery:
$.ajax({
url: 'something.html',
success: function(data) {
//add new elements with data.
//bind new events to elements
}
});
a source to share