Reputation: 83
function getData(id) {
$.getJSON('process.php?action=lookup&id='+id, parseInfo);
return false;
}
// Display data in form
function parseInfo(data) {
if (data.id > 0) {
$('#txtaction').val('update');
$('#txtbook_id').val(data.id);
} else {
$('#txtaction').val('');
$('#txtbook_id').val('');
}
}
Referring to the method above, is this the proper way to populate form fields? Will it cause any problem when calling getData function if i have a long list of form fields to populate and attributes to change?
Thank you in advance for any comments!
Upvotes: 1
Views: 84
Reputation: 163
This seems to be correct. However keep in mind that JSON attribute names can't contain dashes so an alternate way to get around that problem would be:
if (data['id'] > 0) {
$('#txtaction').val('update');
$('#txtbook_id').val(data['id']);
} else {
$('#txtaction').val('');
$('#txtbook_id').val('');
}
Upvotes: 0
Reputation: 1074385
One tweak I'd make is to avoid repeating the selectors and val
calls, too easy to add a field and forget to update one half of the if/else
or the other:
function parseInfo(data) {
var valid = data && data.id > 0;
$('#txtaction').val(valid ? 'update' : '');
$('#txtbook_id').val(valid ? data.id : '');
}
Side note: Doing this manually is fine for very small projects, but for anything of any size, you might look into any of the various MVC and MVVC tools or frameworks. There are many.
Upvotes: 1