How to make my custom script generate a calculated value

Hello all,

I have a custom script that I have written to calculate some values in a child table in my custom doctype.

I want a situation whereby as each item is being selected, they’re automatically calculated, and the total sum of value is populated at the Grand Total field.

Here is my script to achieve this:

 frm.compute_total = function(frm, row){
       var total = 0;
       //loop through the child table
       frm.doc.lease_item.forEach(d=>{
       total = total + d.amount;
       console.log(total);
       frm.set_value('grand_total', total);

//Demand Notice Item Child Table
frappe.ui.form.on('Lease Item', {
    lease_item: function(frm, cdt, cdn){
        // grab the entire record
        let row = locals[cdt][cdn];                 
        frm.check_lease_items_duplicate(frm, row, row.lease_item);
        frm.compute_total(frm, row);
    },

This shows that the script is working, however, "frm.set_value(‘grand_total’, total) doesn’t seem to set the value. I am confused as to what to do next.

Any suggestion will be greatly appreciated. Thanks.

try this :

frappe.ui.form.on('Lease Item', {
    amount: function (frm, cdt, cdn) {
        var row = locals[cdt][cdn];
        var total = 0;
        $.each(frm.doc.lease_item || [], function (i, d) {
            total += parseFloat(d.amount);
        });
        cur_frm.set_value("grand_total", total);
    }

});

Code below is not working, kindly help
frappe.ui.form.on(‘Purchase Order Item’, {
refresh(frm) {
// self.doc.qty_to_received = flt(self.doc.stock_qty)-flt(self.doc.received_qty)
}
})

You should try

refresh(frm) {
frm.doc.qty_to_received = flt(frm.doc.stock_qty)-flt(frm.doc.received_qty)
}

Thanks for your reply, I entered it as

frappe.ui.form.on(‘Purchase Order Item’, {
refresh(frm)
{frm.doc.qty_to_received = (flt(frm.doc.stock_qty)-flt(frm.doc.received_qty));}
});
But its not working. Any suggestion kindly

Is this for a child table?

try:

frappe.ui.form.on('Purchase Order Item', {
    stock_qty: function (frm, cdt, cdn) {
        var row = locals[cdt][cdn];
        if(row.stock_qty && row.received_qty){
            frappe.model.set_value(cdt, cdn, "qty_to_received", row.stock_qty-row.received_qty);
        }
    },
    received_qty: function (frm, cdt, cdn) {
        var row = locals[cdt][cdn];
        if(row.stock_qty && row.received_qty){
            frappe.model.set_value(cdt, cdn, "qty_to_received", row.stock_qty-row.received_qty);
        }
    }

});

Yes, It is Child table (item table) in purchase order

for a child table, the code is slightly different. Refer to this guide, Community Developed Custom Scripts · frappe/erpnext Wiki · GitHub

The section for calculating values in a child table is what you need.