$('#posts_form_data').on('submit', function(e) { const $form = $(this); const number = value => parseFloat(value) || 0; const productType = $form.find('#crc_type').val(); const productValue = number($form.find('#crc_value').val()); const errors = []; const check = (name, price, type, value) => { if (type == 1 && value > 100) { errors.push(`${name}: CRC percentage cannot be more than 100.`); } else if (type == 0 && price !== null && value > price) { errors.push(`${name}: fixed CRC ₹${value} is more than the selling price ₹${price}.`); } }; const $rows = $form.find('.pricing-info-row, [data-crc-price]').filter(function() { const $row = $(this); // The blank starter row is not saved, and inactive rows are not sold return $row.is('[data-crc-price]') ? $row.data('crc-active') == 1 : $row.find('[data-field="mrp"]').val() !== '' && $row.find('[data-field="status"]').val() == 1; }); $rows.each(function() { const $row = $(this); const $value = $row.find('input[name$="[crc_value]"]'); const rowType = $row.find('select[name$="[crc_type]"]').val(); const overridden = $value.val() !== ''; const price = $row.is('[data-crc-price]') ? number($row.data('crc-price')) : number($row.find('[data-field="selling_price"]').val() || $row.find('[data-field="mrp"]').val()); const name = $row.find('.pricing-label-input').val() || $row.data('crc-label') || 'A pricing row'; check(name, price, overridden && rowType !== '' ? rowType : productType, overridden ? number($value.val()) : productValue); }); if (productType == 1 && productValue > 100) { errors.push('CRC percentage cannot be more than 100.'); } const hasPricingRows = $form.find('[data-crc-price]').length > 0 || $rows.length > 0; if (!hasPricingRows && $form.find('#amount').length) { check('This product', number($form.find('#amount').val()), productType, productValue); } if (errors.length) { e.preventDefault(); alert([...new Set(errors)].join('\n')); } });