Reputation: 2736
I have a page which could have anywhere from 1 to up to 100 iterations of a code block - in this code block the fields etc have the same names and ID's in each iteration as it is contained within a for loop.
Below is a simple example of the looped code:
<div id="form" class="form">
<form method="post" id="input_form" action="<?=$PHP_SELF?>" enctype="multipart/form-data">
<input type="text" name="start" id="start">
<input type="text" name="end" id="end">
<input type="text" name="duration" id="duration">
<button type="button" id="calc">Calc</button>
<input type="submit" name="submit" value="Submit">
</form>
</div>
For normal HTML form submit purposes the multiple iterations works fine as only one submit button can be clicked at a time and it then takes the values from start and end and submits.
However, I also need to be able to perform a simple calculation via AJAX on the data and this is where the problem occurs - as I can have 1 to 100 buttons using the same ID it never fires. I have tried appending a value to the end of the ID's (using $i in my for loop for example) so they are then unique but then I cannot use #calc to fire the ajax call as there is no element called calc any longer.
jQuery(document).ready(function () {
$("#calc").click(function () {
var start_date = $("#start").val();
var end_date = $("#end").val();
var dataString = 'start_date=' + start_date + '&end_date=' + end_date;
$.ajax({
type: "POST",
url: "calc.php",
data: dataString,
success: function () {
$('#duration').val(data);
}
});
});
});
I need the ajax call to fire using the correct start and end and then fill in duration in the form the user is working in without knowing how many forms there are or which is in use.
Upvotes: 0
Views: 133
Reputation: 2033
You need to make the listener and selectors relative to the form which the user is using:
You do realise that you cannot have duplications of IDs on the page. They have to be unique. Assuming you change these IDs to classes, I will write the following code:
jQuery(document).ready(function () {
$(".button").click(function () { // add the class button to the submit
var t = $(this);
var start_date = t.prev(".start").val();
var end_date = t.prev(".end").val();
var dataString = 'start_date=' + start_date + '&end_date=' + end_date;
$.ajax({
type: "POST",
url: "calc.php",
data: dataString,
success: function (data) {
t.prev('.duration').val(data);
}
});
});
});
Upvotes: 3
Reputation: 1249
you should not catch the ajax success response
success: function (data)
{
$('#duration').val(data);
}
Upvotes: 1