Fire javascript onchange event programmatically

Recently I was working on a project where I needed to tally a bunch of textbox values using javascript. The textboxes were in a table with 3 columns and about 14 rows. The far column and the bottom row were readonly textboxes used to total the various rows and columns. I wrote some javascript that fired on each textbox’s onblur event so that whenever a textbox value was changed, both the column and row totals would update.

My problem was totalling the far column. Because the textboxes in the far column were readonly, the text was being changed programmatically rather than by a user. Thus, the onchange event was not firing, and the javascript written to total the column was not running.

I turned to Google, and found a little blog entry that showed me how to fix my problem. It was refreshingly simple – test to see if an onchange event exists for the readonly textbox, and then fire the event. So I could total my row, and then fire the total textbox’s onchange event to total the far column. See below for an example.

//sum row values
function addRow(sField, iField, totField)
{

//get row values from textboxes on page
var s = document.getElementById(sField).value;
var i =
document.getElementById(iField).value;

//convert values to numbers
s = Number(s);
i = Number(i);

//add values together
var total = s + i;

//load total textbox in variable
var TotField = document.getElementById(totField);

//set total textbox value to sum of values (format as currency)
TotField.value = '$' + addCommas(total);

//fire onchange event on total textbox (make sure it exists first)
if (TotField.onchange) {TotField.onchange()};

}

Notice the addCommas function call above. This is a nifty little function to format numbers with commas in all the right places — lifted wholesale from another blog entry I found. Thank God for bloggers!!