Reputation: 35
I have a 'Sales Order Item' modal that allows the user to select a product from a Select list. When a user selects a product I then use the onChange event to load related data via Ajax from the product source database into other inputs on the modal (i.e. The product description and cost price).
This works fine when creating an order item, but when the user tries to edit an order item the onChange event fires when the modal is displayed, causing the related data to reload via Ajax, but the user may have changed the original data, so the data always reverts to its original state.
For example, the cost price of item ABC123 is £10 by default, but for this particular sales order, the user sourced it for £8, so when the user created a new 'sales order item' and selected item ABC123, the cost price defaulted to £10, but the user then manually changed it to be £8 (for this sales order item only!). Then, later on, if they try to edit this 'sales order item', the default is reloaded and defaults back to £10.
Please see my onchange code below:
$(document).on('change', '#qsjob-cat', function(){
var newVal = $('#qsjob-cat').val();
$.ajax({ url: "AjaxGetData.wc?ti=cat;cat&fl=title&key=cat:C:"+newVal ,
type: "POST",
success: function(data) {
data = decodeURIComponent(data);
$('#qsjob-des').val(data);
}
});
});
Not sure if it is important or not, but, I'm using the DataTables & Editor plugin for Jquery.
I suspect the onchange events fires because the DataTable\Editor probably inserts the data into each element on modal show, but I'm not sure how else to achieve my objective?
I'm sure there is an obvious answer to this, but I'm relatively new to JS.... lots to learn ;-)
Any advice is greatly appreciated.
Thanks, Chris
Upvotes: 1
Views: 1106
Reputation: 3765
If you know beforehand if an item is beeing created or edited, you could just 'ignore' the first onchange event if you know that the item is beeing edited.
let isEditing = true; // if you know that you are editing
let shouldFire = false;
$(document).on('change', '#qsjob-cat', function(){
if (isEditing && !shouldFire) {
shouldFire = true; // sets it so it fires the next time
return; // returns without firing this time
}
var newVal = $('#qsjob-cat').val();
$.ajax({ url: "AjaxGetData.wc?ti=cat;cat&fl=title&key=cat:C:"+newVal ,
type: "POST",
success: function(data) {
data = decodeURIComponent(data);
$('#qsjob-des').val(data);
}
});
});
Alternatively, you could just fill in the type in your model, then the defaults (e.g. 10$) get loaded and filled in, and then you fill in the user's 8$ custom value.
Upvotes: 1