html – Complicated AJAX update with two selection items

I have a form with two selection items where users can choose a product variant (eg red, green, blue shirt) and quantity.

When changing the variant / quantity, I make an AJAX request to get the price.

The complicated part is: Each variation has its own price and its own quantities. For example, $ 10 and a minimum of 5 (10, 15 …) are available for red shirts. Green shirts cost $ 15, but the amount starts at 3 (6, 9 …).

(Color / shirt just an example, real products are control devices for street lamps 🙂

The problem is if the default value is & # 39; red & # 39; and & # 39; 5 & # 39; is and I too & # 39; green & # 39; change, the price shows 75 USD (AJAX query was green + 5). But green has only quantities of 3, 6, 9 etc.

I could return the minimum amount from my AJAX request, but the user can not update the price if he changes the quantity selection.

The only solution is two doSubmit () functions and two submitAjax (). But that would mean that I have a lot of duplicate code.

HTML

JavaScript

// Product variation, drop-down list for quantity selection
var product_selection = document.querySelector (# product # selection);
var product_variation = document.querySelector (& # 39; # product_variation & # 39;);
var product_quantity = document.querySelector (# product #quantity #);

// event listener to submit the form on change
product_selection.addEventListener (& submit; submitAjax);
product_variation.addEventListener (& # 39; change & # 39 ;, doSubmit);
product_quantity.addEventListener (& # 39; change & # 39 ;, doSubmit);

// Submit Form
Function doSubmit (event) {
product_selection.dispatchEvent (new event (& # 39; submit & # 39;)); // product_selection.submit ();
}

// handle Ajax Submit
Function submitAjax (event) {

// Stop the standard form
event.preventDefault ();

// Ajax request
$ .ajax ({
URL: & # 39; /static/public/ajax/get_product_data.php&#39 ;,
Type: "POST",
data: $ (& # 39; # product_selection & # 39;). serialize (),
Success: Function (Result) {
if (result == 0) {
alert (& # 39; sorry & # 39;);
} else {
setProductData (result);
}
},
Error: Function (jqxhr, status, exception)
alert (& # 39; sorry & # 39;);
}
})
}

// Update product details
Function setProductData (result) {
$ (& # 39; # product_price & # 39;). html (result.price_gross);

// Remove current quantity options
var product_quantity = document.getElementById ("product_quantity");
for (i = product_quantity.options.length - 1; i> = 0; i--) {
product_quantity.remove (i);
}
// ... reapply new quantity options
var c = 0;
for (var i = result.minimum; i <= result.maximum; i + = result.graduation) {
product_quantity.options[c] = new option (i + & # 39; + pwjs.product.unit, i);
if (result.product_quantity == i) {
var setselectedIndex = c;
}
c ++;
}
// product_quantity.selectedIndex = setselectedIndex;
}