Jquery, get label value inside a user control - javascript

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(); });
}

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>

MVC Calculated Fields Html.TextBoxFor Javascript conflict with two functions

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.

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());
});
}

Math.floor() and parseFloat() clash?

$('#pm').val(Math.floor(parseFloat(pm*100/100)));
Full code:
<script type="text/javascript">
function updatePay() {
// Grab all the value just incase they're needed.
var current_price = <?php echo json_encode($current_price); ?>;
var pm = $('#pm').val();
var gg = pm/current_price;
// Set the new input values.
$('#pm').val(Math.floor(parseFloat(pm*100/100)));
$('#gg').val(gg);
}
$('#pm').keyup(updatePay);
$('#gg').keyup(updatePay);
</script>
When I use Math.floor it doesn't allow me to enter a second decimal.
I need my code to be able to allow a second decimal place to be filled in, how can I do this in Javascript?
Try this
$('#pm').val((Math.floor(parseFloat(pm)*100)/100).toFixed(2));
I think you want to round down and allow 2 decimal places,
so if the number is 3546.699433
parseFloat(pm)*100 = 354669.9433
math.floor(354669.9433) = 354669
354669/100 = 3546.69
<script type="text/javascript">
function updatePay() {
// Grab all the value just incase they're needed.
var current_price = <?php echo json_encode($current_price); ?>;
var pm = $('#pm').val();
var gg = pm/current_price;
// Set the new input values.
$('#pm').val((Math.floor(parseFloat(pm)*100)/100).toFixed(2));
$('#gg').val(gg);
}
$('#pm').change(updatePay);
$('#gg').chnage(updatePay);
</script>
If you want something that gets updated on keyup, try something along these lines
Javascript:
document.getElementById("num1").onkeyup = function(){
var val = (Math.floor(parseFloat( document.getElementById("num1").value)*100)/100).toFixed(2);
if(isNaN(val)){
document.getElementById("result").innerHTML = "pm will appear here";
}
else if(val){
document.getElementById("result").innerHTML = val;
} else {
document.getElementById("result").innerHTML = "pm will appear here";
}
}
HTML:
<body>
<input type="button" id="myButton" value="click me"/>
<span id="result"></span>
<input type="text" id="num1" value="1.1111"></div>
</body>
It's hard to tell what you're trying to achieve, but at a guess I suspect you want the values displayed in pm and gg to have two digits of fractional precision. If so:
function updatePay() {
// Grab all the value just incase they're needed.
var current_price = <?php echo json_encode($current_price); ?>;
var pm = parseFloat($('#pm').val()); // Parse here
var gg = pm/current_price;
// Set the new input values.
$('#pm').val(pm.toFixed(2)); // Round to two places and turn back into text
$('#gg').val(gg.toFixed(2)); // " " " " " " " " "
}
Side note: You have this set as a keyup handler on the gg element, but you're always overwriting what the gg element has in it, without using the value in gg at all. If I were a user, I'd find that pretty irritating.

.clone doesn't not appear to be incrementing

this script is suppose to clone a new row of a HTML table. It does not seem to be incrementing the name, id, attributes. What am I doing wrong? The only other thing that is not working is get the value from the previous input id of #endtime_* and putting it in the cloned input id of #starttime_* although I think that is because it does seem to be incrementing as it clones a row.
<script type="text/javascript">
function MaskTime(){
var index = $("#TimeCard tbody>tr").length-1;
$('#endtime_'+index).mask("99:99 aa");
$('#starttime_'+index).mask("99:99 aa");
}
function update_rows(){
$("#TimeCard tbody>tr:odd").css("background-color", "#FFF");
$("#TimeCard tbody>tr:even").css("background-color", "#999");
}
$(document).ready(function() {
$("#addrow").click(function() {
var row = $('#TimeCard tbody>tr:last').clone(true).insertAfter('#TimeCard tbody>tr:last');
var index = $("#TimeCard tbody>tr").length-1;
var endvalue = $('#endtime_'+index-1).val();
$("td:eq(0) select").attr("name", 'type_'+index).attr("id", 'type_'+index).addClass("validate[required]").val('')
$("td:eq(1)").html(" ")
$("td:eq(2) select").attr("name", 'propid_'+index).attr("id", 'propid_'+index).addClass("validate[required]").val('')
$("td:eq(3)").html(" ")
$("td:eq(4) input").attr("name", 'starttime_'+index).attr("id", 'starttime_'+index).addClass("validate[required,custom[timeclock]]").val(endvalue)
$("td:eq(5) input").attr("name", 'endtime_'+index).attr("id", 'endtime_'+index).addClass("validate[required,custom[timeclock]]").val('')
$("td:eq(6)").html(" ")
update_rows();
MaskTime();
return false;
});
});
</script>
For the first part of your question:
It does not seem to be incrementing the name, id, attributes.
Your script isn't giving the proper context for where the tds are for which you want to modify the attribues, etc.
Here's a modification that corrects that, adding a new variable "newrow" (to reduce DOM calls) and modifying the lines of code related to td:eq(#)...
$(document).ready(function() {
$("#addrow").click(function() {
var row = $('#TimeCard tbody>tr:last').clone(true).insertAfter('#TimeCard tbody>tr:last');
var index = $("#TimeCard tbody>tr").length-1;
var endvalue = $('#endtime_'+index-1).val();
var newrow = $("#TimeCard tbody>tr:last");
newrow.children("td:eq(0)").children("select").attr("name", 'type_'+index).attr("id", 'type_'+index).addClass("validate[required]").val('')
newrow.children("td:eq(1)").html(" ")
newrow.children("td:eq(2)").children("select").attr("name", 'propid_'+index).attr("id", 'propid_'+index).addClass("validate[required]").val('')
newrow.children("td:eq(3)").html(" ")
newrow.children("td:eq(4)").children("input").attr("name", 'starttime_'+index).attr("id", 'starttime_'+index).addClass("validate[required,custom[timeclock]]").val(endvalue)
newrow.children("td:eq(5)").children("input").attr("name", 'endtime_'+index).attr("id", 'endtime_'+index).addClass("validate[required,custom[timeclock]]").val('')
newrow.children("td:eq(6)").html(" ")
update_rows();
MaskTime();
return false;
});
});
Also, I'd made a jsfiddle with the above: http://jsfiddle.net/m78UN/2/
I'm not following what you're wanting when you describe your second problem:
The only other thing that is not working is get the value from the previous input id of #endtime_* and putting it in the cloned input id of #starttime_*
...so I've not attempted to address that.
I think you can do everything you're doing in a way simpler way. I don't have your original HTML, but check this out as a possible alternative. It mainly does 3 things:
Removed IDs used for finding things
Caches selectors
Adds classes to time inputs to make them easier to reference
Removed MaskTime() function
Here's the code:
$(document).ready(function() {
var $timecard = $("#TimeCard");
var $tbody = $timecard.find("tbody");
var $rows = $tbody.children("tr");
$("#addrow").click(function(e) {
e.preventDefault(); // clearer than return false
var $lastRow = $tbody.find("tr:last-of-type");
var lastEnd = $lastRow.find(".endTime").val();
var $newRow = $lastRow.clone(true).appendTo($tbody);
var $cols = $newRow.find("td");
var index = $rows.length - 1;
$cols.eq(0).find("select").attr("name", 'type_' + index).addClass("validate[required]").val('');
$cols.eq(1).empty();
$cols.eq(2).find("select").attr("name", 'propid_' + index).addClass("validate[required]").val('');
$cols.eq(3).empty();
$cols.eq(4).find("input").attr("name", 'starttime_' + index).addClass("time startTime validate[required,custom[timeclock]]").val(lastEnd);
$cols.eq(5).find("input").attr("name", 'endtime_' + index).addClass("time endTime validate[required,custom[timeclock]]").val('');
$cols.eq(6).empty();
update_rows(); // no idea what this is
$newRow.find(".time").mask("99:99 aa"); // MaskTime() just did this
});
});

Categories

Resources