How to handle several submit buttons in a form with JQuery?
I need to create 30 buttons, from 1 to 30, whereby each one calls the exact same action script (e.g. all under the same form) where the parameter that is passed to the action script is simply the number of the button pressed (1 to 30).
For example, let's say the action script is process.php, if button 3 is pressed, then I need to pull data from process.php?btn=3, and if button 27 is pressed, then I need to pull data form process.php?btn=27.
What is the easiest, most straight-forward way of doing开发者_JAVA百科 that with JQuery?
Thanks!
Something like this should do it. The beforeSend function is just to show you what is being sent to the server.
$('button').click(function (e) {
e.preventDefault();
var number = $('form button').index(this);
$.ajax('process.php', {
data: 'number='+ number,
beforeSend: function (jqHxR, settings) {
alert(settings.data);
return false;
}
});
});
EDIT: http://jsfiddle.net/EvilAmarant7x/NhMnP/
Assuming you give all of your links the class .number
:
$("a.number").click(function(e) {
e.preventDefault();
window.location.href = 'process.php?btn=' + $(this).text();
});
<a class="number" href="#">1</a>
<a class="number" href="#">2</a>
...
This seems to be the type of thing that is best done on the server side, as in having the server render each href
with the correct param values. I am assuming that is not an option in your case.
EDIT: Asynchrony, as requested:
$("a.number").click(function(e) {
e.preventDefault();
// fill up div with ID="results" with content from server
$("#results").load("process.php", { btn: $(this).text() }, function() {
// callback to do something once the content has loaded
// (perhaps not needed)
});
});
<div id="results"></div>
...
<a class="number" href="#">1</a>
<a class="number" href="#">2</a>
...
See $.load
and $.ajax
.
精彩评论