In my admin area I have over 50 modules that are used by volunteers to maintain database tables. In each module I have a form for editing records and a dataTable for listing all the records. To edit a record the user finds the record in the dataTable and selects/clicks the row. The click activates a table click event when then causes the record information to populate the form as illustrated in the following code.
let rowData = oTable.row(this).data();
$('#bio_name').val(rowData.bio_name);
$('#bio_title').val(rowData.bio_title);
$('#bio_sub_fk').val(rowData.bio_sub_fk);
$('#bio_text_top').val(rowData.bio_text_top);
$('#bio_text_main').val(rowData.bio_text_main);
$('#bio_text_bot').val(rowData.bio_text_bot);
I would like to update the process so that I could call a function to populate the form rather than have to maintain 50+ modules. The call would be
load_Form( prefix, rowData );
and the function would be
function load_Form( prefix, rowData ) {
$('[id^=' + prefix + '_]').each( function() {
// What goes here?
});
}
But I'm at a loss as to what would go in the .each( function() {. I would think something like
$(this).val(rowData.this);
But I don't think the 2nd 'this' is correct. Any help would be greatly appreciated.
TIA James A Wilson www.txfannin.org
I'm not as familiar with jQuery, but I imagine the .each function takes arguments representing the current item.
Check out the documentation for .each to see the arguments it accepts
Here is an implementation in vanilla js. Note the element portion in the .forEach
We can then get the id of the element that we matched, and remove the prefix to get the property to match on our data source.
const dataSource = {
firstName: 'John',
lastName: 'Doe',
age: 45,
};
function populateForm(prefix, data) {
[...document.querySelectorAll(`[id^=${prefix}`)].forEach((element, index, array) => {
const field = element.getAttribute('id').replace(prefix, '');
element.value= data[field];
})
}
populateForm('bio_', dataSource);
<input id="bio_firstName"/>
<input id="bio_lastName"/>
<input id="bio_age"/>