Reputation: 13
I want that my jquery code click multiple times in a submit button inside the following form.
I have a YUI event listener tracking the submit event and It calls a Callback function each time. How can I click once and generate multiple submit events ?
<!DOCTYPE html>
<html>
<head>
<style>
button { margin:10px; }
div { color:blue; font-weight:bold; }
span { color:red; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<form class="forms" id="result_form" method="post" >
<input type="submit" id = "click" value="Sum Result" ></input>
</form>
<button id = "B2">Button #2</button>
<script>
$("#click").click(function () {
alert("Test");
});
$("#B2").click(function () {
for(j=0;j<10;j++)
$("#click").trigger('click');
</script>
</body>
</html>
In the code above when I click on B2 I just get one alert but when I put the submit outside the form I can get the 10 alerts.
Upvotes: 0
Views: 2446
Reputation: 6329
You can POST the form without reloading the page using Ajax. In order to do that you need to first stop the default behavior of the browser when submitting the form. You do that by calling e.preventDefault()
on the submit event. Then you use ajax and serialize the form into data. Both jQuery and YUI provide utilities for doing that:
// jQuery
$('#result_form').on('submit', function (e) {
e.preventDefault();
$.post('cmd/result', $(this).serialize());
});
// YUI
Y.one('#result_form').on('submit', function (e) {
e.preventDefault();
Y.io('cmd/result', {
method: 'POST',
form: { id: this }
});
});
Upvotes: 0
Reputation: 382314
You're submitting a form. The effect is that you leave the page, and so you stop all your scripts. As you didn't precise the action
parameter of the form, it's the current page, so you're simply replacing the current page by itself at the first iteration of your loop.
If you want to make more than one request from one page without reloading, the usual solution is to use ajax.
You could for example do
for(j=0;j<10;j++) {
$.ajax('someurl');
Upvotes: 1