MVC Calculated Fields Html.TextBoxFor Javascript conflict with two functions - javascript

I have the following fields on my form / web page with some fields that I would like to be calculated when a user types. (see image)
Fields - image here
The field Unit Cost is calculated by Case Cost / Case Size. I have that functioning perfectly with the following code
Casesize Textbox
#Html.TextBoxFor(model => model.q_supplierproduct.q_casesize, "{0:#.#}", new { #class = "calc" })
Case Cost Textbox
#Html.TextBoxFor(model => model.q_supplierproduct.q_casecost, "{0:#.#}", new { #class="calc"})
Unit Cost Textbox
#Html.TextBoxFor(model=> model.q_unitcost, "{0:#.#}", new { #class = "calc" })
Function
#* Calculate Unitcost value *#
<script>
var url = '#Url.Action("CalculateUnitCost", "CalculateValues")';
$('.calc').change(function () {
//get the values of the texboxes
var casecost = $('#q_supplierproduct_q_casecost').val();
var casesize = $('#q_supplierproduct_q_casesize').val();
//check if field entries are valid
if (casecost == '' || casesize == '' || isNaN(casecost) || isNaN(casesize)) { return; }
$.post(url, { Q_casecost: casecost, Q_casesize: casesize }, function (response) {
$('#q_unitcost').val(response);
});
});
</script>
Controller
public class CalculateValuesController : Controller
{
[HttpPost]
public JsonResult CalculateUnitCost(double Q_casecost, double Q_casesize)
{
var result = Computation.GetUnitCost(Q_casecost, Q_casesize);
return Json(result.ToString("#.#"));
}
Method
public class Computation
{
public static double GetUnitCost(double Q_casecost, double Q_casesize)
{
double unitcostresult = Q_casecost / Q_casesize;
return unitcostresult;
}
Just to mention again, this code works as expected, when I change the values in casesiez and casecost, the unitcost field updates accordingly. The next thing I wanted to achieve was to calculate the profit field based on a values entered in the price field minus unit cost field (which is a previously calculated field). I went on to add a second script for that field plus the respective calculations in the controller and method
See two scripts image
<script>
var url = '#Url.Action("CalculateProfit", "CalculateValues")';
$('.calc').change(function () {
//get the values of the texboxes
var sellprice = $('#q_sellprice').val();
var unitcost = $('#q_unitcost').val();
//check if field entries are valid
if (sellprice == '' || unitcost == '' || isNaN(sellprice) || isNaN(unitcost)) { return; }
$.post(url, { Q_sellprice: sellprice, Q_unitcost: unitcost }, function (response) {
$('#q_profit').val(response);
});
});
from this point onwards with this addition, unit cost field stops working (no update when data is entered), but profit field will calculate accordingly if I type values in unit cost and price field. (new scripts stops the first one from working as intended). What am I missing here?
Is it because of the common unit cost field in both scripts that causing the issue? How do I fix?

After reading the comments from Stephen and Tetsuya I changed the code to the following, and that solved my problem. The two fields unitcost and profit are updating now based on the respective changed fields. I do not call any action method here and I am doing all calculations in javascript as advised.
<script>
function calculate()
{
//Fields that are used for calculations
var casecost = parseFloat($('#q_supplierproduct_q_casecost').val());
var casesize = parseFloat($('#q_supplierproduct_q_casesize').val());
var price = parseFloat($('#q_sellprice').val());
//Calculations
var unitcost = casecost / casesize; // get unitcost from casecost FIELD and casesize FIELD
var profit = price - unitcost; // get profit from price FIELD and unicost CALCULATED value
//set results to the updating fields
$('#q_unitcost').val(unitcost.toFixed(2));
$('#q_profit').val(profit.toFixed(2));
}
$(document).ready(function () {
//calculate();
//calculate everytime these following fields change
$('#q_supplierproduct_q_casecost').change(calculate);
$('#q_supplierproduct_q_casesize').change(calculate);
$('#q_sellprice').change(calculate);
$(unitcost).change(calculate);
});
</script>
Hope this helps someone else down the road.

Related

Subtract amount on form submit JavaScript / JQuery

I have a checkout page, where I would like to implement a new feature: subtract from total cart value a certain amount, introduced in an input.
Example: There is 1 item in cart, with value of 10.00$. If user typed 100 in that input, then he would have a discount of 1$ (100 pts = 1$ in this example) and the final value of the cart would be 9.00$. Since I'm using some integrated apps for getting/calculating item value, total cart value, etc. I would like to get some generic code, which I would eventually adjust, to link with my existing code, functions, etc.
The function I have should have these features:
create form
get input value
subtract used points from user's total amount (for example totalPts = 1000)
subtract from cart total value used points, converted into $ (100pts = 1$)
For now, my function looks like this:
function appendRefferalPoints() {
const totalPts = 1000;
// creating form - ok
$form = $('<form id="refForm" class="coupon-form" action></form>');
$form.append(
'<input type="text" id="refValue" name="refInput" class="coupon-value input-small" >'
);
$form.append('<button type="submit" class="btn">Aplica</button>');
$("body").append($form);
// get input value - not ok
$("#refForm").submit(function () {
let value = 0;
$.each($("#refForm").serializeArray(), function (i, field) {
value[field.name] = field.value;
});
});
// subtraction from totalPts logic - not ok
let rez = totalPts - value;
console.log("Final Rez: " + rez);
// subtraction converted pts from cart value logic
}
Now when I submit the form I only url changes from /checkout#/cart to /checkout/?refInput=512#/cart
function appendRefferalPoints() {
const totalPts = 1000;
let cartValue=10;
let discount=0;
let inputValue = 0;
// creating form - ok
$form = $('<form id="refForm" class="refForm coupon-form" ></form>');
$form.append(
'<input type="text" id="refValue" name="refInput" class="coupon-value input-small" value="100" >'
);
$form.append('<button id="btnClick" class="btn">Aplica</button>');
$("body").append($form);
$(document).on("submit", "#refForm", function(e){
//getting input value while submitting form
inputValue=$("#refValue").val();
//converting 100 pts to 1 dallor
discount=inputValue/100;
//calculating balance pts
let balancePts = totalPts - parseInt(inputValue);
//calculating final amount
let finalCartValue=cartValue-discount;
alert("finalCartValue"+finalCartValue);
});
}
appendRefferalPoints();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

How to read a sublist data in netsuite?

I am new to suitescript. Openly telling I hardly wrote two scripts by seeing other scripts which are little bit easy.
My question is how can read a data from sublist and call other form.
Here is my requirement.
I want to read the item values data highlighted in yellow color
When I read that particular item in a variable I want to call the assemblyitem form in netsuite and get one value.
//Code
function userEventBeforeLoad(type, form, request)
{
nlapiLogExecution('DEBUG', 'This event is occured while ', type);
if(type == 'create' || type == 'copy' || type == 'edit')
{
var recType = nlapiGetRecordType(); //Gets the RecordType
nlapiLogExecution('DEBUG', 'recType', recType);
//
if(recType == 'itemreceipt')
{
nlapiLogExecution('DEBUG', 'The following form is called ',recType);
//var itemfield = nlapiGetFieldValue('item')
//nlapiLogExecution('DEBUG','This value is = ',itemfield);
var formname = nlapiLoadRecord('itemreceipt',itemfield);
nlapiLogExecution('DEBUG','This value is = ',formname);
}
}
}
How can I proceed further?
I want to read that checkbox field value in the following image when i get the item value from above
I recommend looking at the "Sublist APIs" page in NetSuite's Help; it should describe many of the methods you'll be working with.
In particular you'll want to look at nlobjRecord.getLineItemValue().
Here's a video copmaring how to work with sublists in 1.0 versus 2.0: https://www.youtube.com/watch?v=n05OiKYDxhI
I have tried for my end and got succeed. Here is the answer.
function userEventBeforeLoad(type, form, request){
if(type=='copy'|| type =='edit' || type=='create'){
var recType = nlapiGetRecordType(); //Gets the RecordType
nlapiLogExecution('DEBUG', 'recType', recType);
//
if(recType == 'itemreceipt')
{
nlapiLogExecution('DEBUG', 'The following form is called ',recType);
var itemcount = nlapiGetLineItemCount('item');
nlapiLogExecution('DEBUG','This value is = ',+itemcount);
for(var i=1;i<=itemcount;i++)
{
var itemvalue = nlapiGetLineItemValue('item','itemkey',i);
nlapiLogExecution('DEBUG','LineItemInternalID = ',itemvalue);
var itemrecord = nlapiLoadRecord('assemblyitem', itemvalue);
nlapiLogExecution('DEBUG','BOM= ',itemrecord);
if(itemrecord == null){
var itemrecord = nlapiLoadRecord('inventoryitem', itemvalue);
nlapiLogExecution('DEBUG','BOM= ',itemrecord);
}
var value = itemrecord.getFieldValue('custitem_mf_approved_for_dock_to_stock');
nlapiLogExecution('DEBUG',"Checkboxvalue = ",value);
if(value == 'F'){
nlapiSetLineItemValue('item','location',i,9);
nlapiSetLineItemDisabled ('item','location',false,i );
}
else{
nlapiSetLineItemValue('item','location',i,1);
nlapiSetLineItemDisabled ('item','location',true,i );
}
}
}
}
}

fill in a field with the concatenation of 2 other fields on load before add

I have a PHP page to add data to database the form has the fields:
BalanceNo, Customer, InvoiceNo, I am using javascript to fill on the fly ; on load in the field BalanceNo with the value of Customer and InvoiceNo which would look like Nicolas-009or somthing like that
I wrote this code but it fills BalanceNo only with the value of customerNo
var ctrl11 = Runner.getControl(pageid, 'InvoiceNo');
var ctrl1 = Runner.getControl(pageid, 'Customer');
var ctrl2 = Runner.getControl(pageid, 'BalanceNo');
function CalNo()
{
var value2=ctrl1.getValue();
var value1=ctrl11.getValue();
ctrl2.setValue(value2,value1);
};
ctrl11.on('change',function(e){ CalNo(); } );
ctrl1.on('change',function(e){ CalNo(); } );
Please Help

In Jquery take a different values from single text box id

I am using Data Table in jquery. So i passed one input type text box and passed the single id. This data table will take a multiple text box. i will enter values manually and pass it into the controller. I want to take one or more text box values as an array..
The following image is the exact view of my data table.
I have marked red color in one place. the three text boxes are in same id but different values. how to bind that?
function UpdateAmount() {debugger;
var id = "";
var count = 0;
$("input:checkbox[name=che]:checked").each(function () {
if (count == 0) {
id = $(this).val();
var amount= $('#Amount').val();
}
else {
id += "," + $(this).val();
amount+="," + $(this).val(); // if i give this i am getting the first text box value only.
}
count = count + 1;
});
if (count == 0) {
alert("Please select atleast one record to update");
return false;
}
Really stuck to find out the solution... I want to get the all text box values ?
An Id can only be used once; use a class, then when you reference the class(es), you can loop through them.
<input class="getValues" />
<input class="getValues" />
<input class="getValues" />
Then, reference as ...
$(".getValues")
Loop through as ...
var allValues = [];
var obs = $(".getValues");
for (var i=0,len=obs.length; i<len; i++) {
allValues.push($(obs[i]).val());
}
... and you now have an array of the values.
You could also use the jQuery .each functionality.
var allValues = [];
var obs = $(".getValues");
obs.each(function(index, value) {
allValues.push(value);
}
So, the fundamental rule is that you must not have duplicate IDs. Hence, use classes. So, in your example, replace the IDs of those text boxes with classes, something like:
<input class="amount" type="text" />
Then, try the below code.
function UpdateAmount() {
debugger;
var amount = [];
$("input:checkbox[name=che]:checked").each(function () {
var $row = $(this).closest("tr");
var inputVal = $row.find(".amount").val();
amount.push(inputVal);
});
console.log (amount); // an array of values
console.log (amount.join(", ")); // a comma separated string of values
if (!amount.length) {
alert("Please select atleast one record to update");
return false;
}
}
See if that works and I will then add some details as to what the code does.
First if you have all the textbox in a div then you get all the textbox value using children function like this
function GetTextBoxValueOne() {
$("#divAllTextBox").children("input:text").each(function () {
alert($(this).val());
});
}
Now another way is you can give a class name to those textboxes which value you need and get that control with class name like this,
function GetTextBoxValueTwo() {
$(".text-box").each(function () {
alert($(this).val());
});
}

Jquery, get label value inside a user control

I need to make a calculation in an asp.net page with the value from a usercontrol label.
the user control label is:
<asp:Label ID="LblInvoicePriceValue" runat="server" ></asp:Label>
I include it like this:
<Controls:VehicleInformation ID="VehicleInformationControl" runat="server" />
And my jquery function is something like:
Please see point 1 and 2.
<script type="text/javascript">
$(document).ready(function () {
alert('call function to do calculation here');
// 1. Find in the vehicle information user control the invoiced ammount label
// 2. Find the vat excluded value **after** it was typed in the textbox
// 3. If invoiced ammount is greater than zero, then
// 3.a Find Label Percentage
// 3.b Label.Text = (AmmountWithoutVat/InvoicedAmmount)*100 + '%'
});
</script>
HTML generated:UPdate1
For the label:
<span id="MainContent_VehicleInformationControl_LblInvoicePriceValue" class="bold"></span>
For the textbox:
<input name="ctl00$MainContent$TxtVatExcluded" type="text" id="TxtVatExcluded" class="calculation" />
Update 2:
<script type="text/javascript">
$(document).ready(function () {
alert('call function to do calculation here');
$("#TxtVatExcluded").keypress(function() {
var invoiceprice = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
var vatexcluced = $("#TxtVatExcluded").val();
var lblPercentage = $("#MainContent_LblPercentage");
if (invoiceprice > 0) {
lblPercentage.text((vatexcluced / invoiceprice) * 100);
}
})
// 1. Find in the vehicle information user control the invoiced ammount label
// 2. Find the vat excluded value after it was typed in the textbox
// 3. If invoiced ammount is greater than zero, then
// 3.a Find Label Percentage
// 3.b Label.Text = (AmmountWithoutVat/InvoicedAmmount)*100 + '%'
});
</script>
var label_text = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
$("#TxtVatExcluded").val(label_text);
UPDATE
If you want to check if the textfield is blank then only do copy the label then use following code
var label_text = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
var txt = $("#TxtVatExcluded").val();
if(txt.length==0)
{
$("#TxtVatExcluded").val(label_text);
}
You can use the rendered ID of the elements to get the values using jQuery
var lbl = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
var tbox = $("#TxtVatExcluded").val();
Later when the calculation is complet, you can update the label text as
$("#MainContent_VehicleInformationControl_LblInvoicePriceValue").html("new label");
Update:
To use the logic, where the user types, you have to bind the function to keypress/keyup/keydown event
$("#myinputbox").keypress(function() {
var lbl = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
var tbox = $("#TxtVatExcluded").val();
//... so on
}
Update 2:
Since, you are attempting to calculate with the values, it is safer to make sure, there are numbers in the first place. For that, you can use parseInt(), parseFloat() as needed.
$("#TxtVatExcluded").keypress(function() {
var invoiceprice = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
var vatexcluced = $("#TxtVatExcluded").val();
var lblPercentage = $("#MainContent_LblPercentage");
if (invoiceprice > 0) {
lblPercentage.text((parseInt(vatexcluced) / parseInt(invoiceprice)) * 100);
}
})
This will get you the value of the label control:
function Calculate()
{
var InvoicedAmmount = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
var AmmountWithoutVat = $("#TxtVatExcluded").val();
var Result = (AmmountWithoutVat/InvoicedAmmount)*100
$("#OutputLabel").html(Result + " %");
}
You can attach and onBlur event to your text box to fire your calculation when they leave the text box - you wouldn't really want to re-calculate the amount as they typed.
$(document).ready(function ()
{
$("#TxtVatExcluded").bind("blur",function(){ Calculate(); });
}

Categories

Resources