I have a function that adds change events for form items based on the row name(uses the database to get these).
Heres the current function:
$sql = "SELECT * FROM product WHERE storeno = '1' ORDER BY descript";
$result = mssql_query($sql, $msConnection);
if ($result && mssql_num_rows($result) > 0) {
while ($row = mssql_fetch_object($result)) {
$sku = trim($row->mas90sku);
$JQueryReadyScripts .= "
$('#newCount_" . $sku . "_row .cases').change(function() {
var count = 0;
$('#newCount_" . $sku . "_row .cases').each(function () {
count += parseFloat($(this).val());
});
$('#cases_total_" . $sku . "').text(count);
});
$('#newCount_" . $sku . "_row .units').change(function() {
var count = 0;
$('#newCount_" . $sku . "_row .units').each(function () {
count += parseFloat($(this).val());
});
$('#units_total_" . $sku . "').text(count);
});";
}
mssql_free_result($result);
}
How can I consolidate this into a call that affects every row so that I can get rid of the DB portion and have just 2 pieces (or 1) of code instead of 2 for every row.
This has no dependency on PHP, just use it as a regular script.
It uses
.on()event delegation, so it requires jQuery 1.7+. For earlier versions of jQuery you can use.delegate()for the same effect.I’d recommend giving all your rows a common CSS class, so that the not-so-nice
$('*[id^=newCount_]')can be replaced with something simpler, but that’s a cosmetic change.