Reputation: 284
I've a large form using AJAX so save. It uses a bunch of JS stored in an external JS file. They looks like this:
function milestone09() {
$.post('./post.3.AIGs2GRA.php?data=' + (secData), $('#milestone09').serialize(), function(data) {
$("#errorText_milestone09").html(data.errorText_milestone09);
$("#resultImg_milestone09").html(data.resultImg_milestone09);
$("#errorStatusReport").html(data.errorStatusReport);
}, 'json' );
}
function dateExp09() {
$.post('./post.3.AIGs2GRA.php?data=' + (secData), $('#dateExp09').serialize(), function(data) {
$("#errorText_dateExp09").html(data.errorText_dateExp09);
$("#resultImg_dateExp09").html(data.resultImg_dateExp09);
$("#errorStatusReport").html(data.errorStatusReport);
}, 'json' );
}
function milestone10() {
$.post('./post.3.AIGs2GRA.php?data=' + (secData), $('#milestone10').serialize(), function(data) {
$("#errorText_milestone10").html(data.errorText_milestone10);
$("#resultImg_milestone10").html(data.resultImg_milestone10);
$("#errorStatusReport").html(data.errorStatusReport);
}, 'json' );
}
function dateExp10() {
$.post('./post.3.AIGs2GRA.php?data=' + (secData), $('#dateExp10').serialize(), function(data) {
$("#errorText_dateExp10").html(data.errorText_dateExp10);
$("#resultImg_dateExp10").html(data.resultImg_dateExp10);
$("#errorStatusReport").html(data.errorStatusReport);
}, 'json' );
}
Etc, with triggers like this:
$("document").ready(function() {
$("#milestone09").blur(milestone09);
$("#dateExp09").blur(dateExp09);
$("#milestone10").blur(milestone10);
$("#dateExp10").blur(dateExp10);
})
This is just a section of many I have - and they work fine. Problem is, I am now making a form that has a large table of user input data in it, which will increase these triggers and functions to well over 100 for the one form. There has to be an easier way for me to write this JS and not have to define them each individually like this, surely? The id, and name of each text input field is consistent with the trigger and following function name. So can't I use some sort of loop function, or something? Advice welcome!
And yes I am using jQuery.
Upvotes: 0
Views: 52
Reputation: 25634
A very simple way is to grab the ID and insert it in the right places:
function blurHandler() {
var id = this.id;
$.post('./post.3.AIGs2GRA.php?data=' + secData, $('#'+id).serialize(), function(data) {
$("#errorText_"+id).html(data['errorText_'+id]);
$("#resultImg_"+id).html(data['resultImg_'+id]);
$("#errorStatusReport").html(data.errorStatusReport);
}, 'json' );
}
// If you also have textareas or selects, change this
$('input').blur(blurHandler);
Upvotes: 4