jQuery Inner Submit Function Does Not Work
I have a problem with this jQuery code. It doesn't work as expected:
$('#select_dropdown').change ( function(){
$('#form_to_submit').submit( function(event){
$.post("process.php", { name: "John" },
function(data) {
alert("Data Loaded: " + data);
});
});
});
However, this works:
$('#select_dropdown').change ( function(){
$('#form_to_submit').submit();
});
I wonder why the internal function on submit doesn't work. When a user selects a value from a dropdown, the form must be submitted. The second set of codes wor开发者_如何学Gok but if I add an inner function to submit, it doesn't.
Basically, I want to do some ajax call after the user select on the dropdown.
The first code is creating an event handler for submit event on selector $('#list_count') most likely a form element. The second code is calling the submit method on that element. The first one would be triggered when you submit the form using any method but it itself would not submit the form. What are you trying to do?
EDIT
Do you want to do this
$('#select_dropdown').change ( function(){
$.post("process.php", { name: "John" }, function(data) {
alert("Data Loaded: " + data);
});
});
Here is what you can do:
$("#form_to_submit").submit(function(){
//do your post stuff here
});
$('#select_dropdown').change ( function(){
$("#form_to_submit").submit()
});
What I am doing is:
- Define the handler for submit event of
form_to_submit
- Define the hander when user do the selection on
select_dropdown
, which invokes an submit even on the form.
=================
if you have the code
$('#list_per_page').change ( function(){
$('#list_count').submit( function(event){
alert('It Works!');
});
});
and
$('#list_count').submit();
then it will work. Reason being that for the "It Works" to appear, you need to trigger a submit event.
The first block is adding a handler to the submit event when the change event happens. So when #list_per_page
changes, a submit event handler will be added to #list_count
element.
The second block is just firing a submit even on #list_count; therefore, invoking the handler you added in the fist block.
Keep in mind that the evens happen asynchronously, it seems like you are expecting your code to run sequentially.
My code above is NOT a solution to you're problem; it is for demonstration purpose only. Please tell us what you want to achieve then people can suggest some best practices to help you :-)
精彩评论