As a newcomer to JS, I've scoured countless posts for solutions, but nothing seems to work for me. The issue arises when trying to abstract the code to handle all variables rather than just explicitly expressed values.
I am open to alternative methods, but based on my limited knowledge, this is what I have come up with so far.
The challenge lies in managing a large form with nearly 400 fields for mobile data acquisition. Each piece of data should be sent as it's entered for flexibility and edits until final submission. A green dot is displayed to confirm successful storage, utilizing a <span>
with an id named after each field (e.g., FormFieldAStatus).
Form snippet:
<input type="text" class="form-textbox validate[required]" id="input_1" name="formFieldA" size="20" onchange="saveData(); readData()" />
<span class="ajax-success" id="formFieldAStatus"></span>
The existing working code:
function readData() {
new Ajax.Request('AjaxRead.php', {
method: 'post',
parameters: $('Worksheet').serialize(true),
onSuccess: function(transport) {
var icon = '<img src="images/greendot.png" align="bottom" style="margin-right:5px;">';
if (transport.responseText) {
var json=transport.responseText.evalJSON();
if(json.formFieldA) {
var status = $('formFieldAStatus');
status.update(icon); }
if(json.formFieldB) {
var status = $('formFieldBStatus');
status.update(icon); }
if(json.formFieldC) {
var status = $('formFieldCStatus');
status.update(icon); }
}
},
onFailure:function(){ alert('Something went wrong...') }
});
}
However, manually checking each field for updates is not feasible with 400 lines of code.
Here's the code that should work but doesn't:
function readData() {
new Ajax.Request('AjaxRead.php', {
method: 'post',
parameters: $('Worksheet').serialize(true),
onSuccess: function(transport) {
var icon = '<img src="images/greendot.png" align="bottom" style="margin-right:5px;">';
if (transport.responseText) {
var json=transport.responseText.evalJSON();
for(var key in json) {
if(!json[key]=='') {
var statusName=key+'Status';
// Various methods attempted, none successful
var status = $(statusName);
var status = $(window[statusName]);
var status = $(key+'Status');
var status = $(window[key+'Status']);
eval("var status = $('"+key+"Status');");
// Is there a solution among these?
status.update(icon); }
}
}
},
onFailure:function(){ alert('Something went wrong...') }
});
}
Your insight would be greatly valued. If there is a more efficient approach, I am eager to learn about it.
Thank you.
Additional details:
I added the following for reference:
console.log('statusname: '+statusName);
console.log('status: '+status);
console.log('status Object: '+Object.inspect(status));
The output was:
statusname: fieldNameAStatus
status: [object HTMLElement]
status Object: <span id="fieldNameAStatus" class="ajax-success">
for each attempted method,
When uncommenting:
status.update(icon);
The result changed to:
statusname: formIDStatus
status: null
status Object: null
Any ideas?