What I'm trying to do:
I have a single bootstrap modal which contains a form that I'm using to ADD records and at the same time UPDATE.
What I have:
A two buttons to SHOW this modal that calls a particular method depending on what the action is.
- For adding, it clears the fields on the form. (
showReferenceModal()
) - For updating, it load the information on their corresponding fields. (
loadReferencesDetails(referenceId)
)
The methods:
function showReferenceModal() {
...
$('#referenceId').val("");
$('#name').val("");
$('#addr').val("");
$('#tel').val("");
$('#updateInfo').html("");
$('#modal').modal('show');
}
function loadReferencesDetails(referenceId) {
...
$.ajax({
...
dataType: 'json'
}).done(function(response) {
$('#referenceId').val(response.referenceId);
$('#name').val(response.name);
$('#addr').val(response.addr);
$('#tel').val(response.tel);
var updateInfo = "";
...
$('#updateInfo').html(updateInfo);
$('#modal').modal('show');
});
}
Possible Improvements:
Is there a better way to clear the fields all at once? Because if the form becomes bigger, then the method to show the modal will get bigger too. It's okay for now, but I'm thinking about extensibility. I'm new to jQuery so I don't really know if there's a method to do this.
For loading the details on the form, As you can see, the response from my Servlet returns a JSON with the SAME property name as the ID of the FIELD it belongs to. Maybe there's a shortcut for this too?
By the way, I have multiple modal, which has their own set of these two methods. Any tip so I can just use a single method for different modals instead of creating their own
showXXXModal
andloadXXXDetails()
?
Any suggestions would be greatly appreciated.