Having some trouble getting this right. I'm very new to jQuery, so trying to get better and learn.
Currently I am getting 2 different values from a html table using the following code
var sellPrice = $('.qt').find("tr:eq(2)").find("td:eq(4)").html();
var buyPrice = $('.break .main-col .qt').find("tr:eq(2)").find("td:eq(4)").html();
These both output a value such as $13,000,000
I am then wanting to subtract 1 from these values (making it $12,999,999) before pasting them to an input as such
$('input[name="sell"]').val(sellPrice);
$('input[name="buy"]').val(buyPrice);
However, I am having some trouble with how to subtract $1 from these.
I tried using sellPrice--; but without success.
I've also tried adding - 1; at the end of each variable, but did not succeed either.
I tried to test something like this, but did not work either.
var minusOne = -1;
var getCurrentSellPrice = $('.qt').find("tr:eq(2)").find("td:eq(4)").html();
var getCurrentBuyPrice = $('.break .main-col .qt').find("tr:eq(2)").find("td:eq(4)").html();
var sellPrice = (getCurrentSellPrice - minusOne);
var buyPrice = (getCurrentBuyPrice - minusOne);
$('input[name="sell"]').val(sellPrice);
$('input[name="buy"]').val(buyPrice);`
Trying my best to familiarize myself with jQuery :)
Any help is much appreciated!
Solved using this
var getCurrentSellPrice = $('.qt').find("tr:eq(2)").find("td:eq(4)").html();
var getCurrentBuyPrice = $('.break .main-col .qt').find("tr:eq(2)").find("td:eq(4)").html();
var sellPrice = Number(getCurrentSellPrice.replace(/[^0-9\.]+/g,"")) - 1;
var buyPrice = Number(getCurrentBuyPrice.replace(/[^0-9\.]+/g,"")) + 1;
$('input[name="sell"]').val(sellPrice);
$('input[name="buy"]').val(buyPrice);
Since your numbers contain currency symbol and are strings, you need to convert them to proper numbers before subtracting them. See the answer below.
How to convert a currency string to a double with jQuery or Javascript?
Related
I am developing a simple application form where I am calculating experiences from maximum three employers. Now I want to add them up . The experiences are in the form of X years Y months and Z days. I have written following javascript function --
function total(){
var td;
var fd=parseInt(document.getElementById("LoS_days1").value);
var sd=parseInt(document.getElementById("LoS_days2").value);
var ld=parseInt(document.getElementById("LoS_days3").value);
var tm;
var fm=parseInt(document.getElementById("LoS_months1").value);
var sm=parseInt(document.getElementById("LoS_months2").value);
var lm=parseInt(document.getElementById("LoS_months3").value);
var ty;
var fy=parseInt(document.getElementById("LoS_year1").value);
var sy=parseInt(document.getElementById("LoS_year2").value);
var ly=parseInt(document.getElementById("LoS_year3").value);
td = (fd +sd +ld);
var rd = td%30;
var cm = Math.floor(td/30);
document.getElementById("Totalexp_day").value=rd;
tm = (cm + fm +sm +lm);
var rm = tm%12;
var cy = Math.floor(ty/12);
document.getElementById("Totalexp_month").value=rm;
ty = (cy + fy +sy +ly);
document.getElementById("Totalexp_year").value=ty;
}
I am getting a NaN message in each of the Totalexp_day, Totalexp_month and Totalexp_day field. Earlier I had some modified code that was not showing NaN message but it was not showing the desired results. Kindly suggest what to do to eliminate these two errors.
parseInt(document.getElementById("LoS_days1").value)
if the first character of the string cannot be converted to a number, parseInt will return NaN.
To avoid this, you can so something like is suggested here:
parseInt(document.getElementById("LoS_days1").value) || 0
If document.getElementById("Totalexp_day").value is empty then also it will return NaN. Make sure you have some number there.
Second alternative is reading document.getElementById("Totalexp_day").innerHTML and then applying parseInt
Probably you alert or console log the document.getElementById("Totalexp_day").value you would be more clearer why this problem is comming
I'm trying to create a script that get some values from several selectboxes and then do some math with them.
The problem is that the script need to be placed in a SaaS enviroment so my options of doing stuff are every limited. The way described below is the only way to do this.
The problem I'm facing is that I can receive the correct values from the selectboxes but I can't convert them to 2 decimals. Further I can't get the initial value adviesprijs converted to just eg. 1500 instead of 1.5 or 1.500.00. I really can't see what I'm doing wrong.
I've created a fiddle here I think that describes my problem best!
My script
function update_amounts() {
var perc = '10' || 0; //this is a value from a Twig tag. Not relevant for question!
var korting = ((100-perc)/100);
var adviesprijs = '€1.500,00'.replace(/[^\d.]/g, ''); //gives 1.5 or 1.500.00 etc..
var adviesprijsValue = parseFloat(adviesprijs) || 0;
var sum = 0.0;
$('#product_configure_form .product-configure-custom-option select').each(function () {
var optionText = $(this).find('option:selected').text();
var matches = optionText.match(/\(([^)]+)\)/g) || [];
if (matches.length > 0) {
var priceText = matches[matches.length - 1];
if (priceText.indexOf("€") > -1) {
var priceClean = priceText.replace(/[^0-9\+\-\.\,]/g, '');
var priceValue = parseFloat(priceClean) || 0;
sum += priceValue;
}
}
});
var sum2 = sum+adviesprijsValue;
var sumBtw = (sum2*1.21).toFixed(2);
$('#amount').text('€' +sum2);//
$('#amountBtw').html('(€'+sumBtw+' - Incl. 21% BTW)');//.toFixed(2)
}
$(document).ready(function(){
$( "#product_configure_form").on("change", ".product-configure-custom-option select", update_amounts);
});
The HTML is pretty long so best is to take a look at the Fiddle.
Can anybody help me to make a correct calculation...?!
Thx in advance
Your conversion from Dutch formatting to normal float formatting is incorrect.
Consider using:
.replace(/[^\d,]/g,"").replace(",",".")
Working example: http://jsfiddle.net/pgaphma3/3/
EDIT
To allow also a plus or minus sign use /[^\d,\-+]/g
Hello I'm yet again stuck on d3...
I'd like to know how to use a thousand seperator on a variable all the examples I've managed to find seem to be on static data.
This is what I've tried so far:
d3.csv("OrderValueToday.csv", function(obj) {
var text = 'Today = £';
var totalSales = text + d3.format(",") + obj[0].Today;
svgLabel = d3.select("#label").append("h2")
.text (totalSales);
});
However it just outputs a load a stuff on the webpage this is it:
Today = £function (n){var e=d;if(m&&n%1)return"";var u=0>n||0===n&&0>1/n?(n=-n,"-"):a; if(0>p){var c=Zo.formatPrefix(n,h);n=c.scale(n),e=c.symbol+d}else n*=p;n=g(n,h);var x=n.lastIndexOf("."),M=0>x?n:n.substring(0,x),_=0>x?"":t+n.substring(x+1);!s&&f&&(M=i(M));var b=v.length+M.length+_.length+(y?0:u.length),w=l>b?new Array(b=l-b+1).join(r):"";return y&&(M=i(w+M)),u+=v,n=M+_,("<"===o?u+n+w:">"===o?w+u+n:"^"===o?w.substring(0,b>>=1)+u+n+w.substring(b):u+(y?n:w+n))+e}20000
So all I want is to be able to make the totalSales value have thousand separators so like 20,000 everything else I've tried doesnt do anything. I've read this https://github.com/mbostock/d3/wiki/Formatting but didnt see what I could do for my scenario.
Any help would be greatly appreciated. Cheers
Specifying a d3.format returns a formatting function, which you must then call as a function, passing in the number to be formatted as an argument:
var myNumber = 22400;
d3.format(',')(myNumber); // returns '22,400'
Sometimes you will see a format function stored as a variable like this:
var commaFormat = d3.format(',');
commaFormat(1234567); // returns '1,234,567'
In your case, you could do the following:
var totalSales = text + d3.format(',')(obj[0].Today);
I would like to find difference between two fields using JavaScript in iText.
I am able to find the sum of them using below code:
PdfStamper stamperResult = new PdfStamper(readersectionResult, new FileOutputStream(RESULT_NEW));
stamperResult .addJavaScript("var nameField = this.getField(\"total\");"+ "nameField.setAction(\"Calculate\",'AFSimple_Calculate(\"SUM\",\"total1\", \"total2\")')");
Is there any way to find the difference using 'AFSimple_Calculate' similar to what I did in the above code snippet?
Thanks for editing! I tried your suggestion but it does not seem to work for some reason.
stamperResult.addJavaScript(" var total1 = this.getField(\"value1\"); var total2 = this.getField (\"value2\"); var subtr = this.getField(\"total\"); subtr.value = total1.value - total2.value;");
I separated newlines by spaces and added right escape characters.
I was also thinking of using a different logic for subtraction using AF methods : like this
stamperResult.addJavaScript("var nameField = this.getField(\"total\");"+ "nameField.setAction(\"Calculate\",'AFSimple_Calculate(\"SUM\",\"total1\", \"-total2\")')");
In the above code I was trying to add -(negative value) to total 2 so that it will be subtracted from total1 though the AF method is still 'SUM'.
But that does not work.
The below simple code seem to work :
stamperResult.addJavaScript("var nameField = this.getField('total');" +
"nameField.setAction('Calculate'," +
"'subtract()');" +
"" +"function subtract(){this.getField('total').value
= (this.getField('total_1').value -this.getField('total_2').value); }");
I updated your question because it contained many spelling errors. I didn't edit the code snippet because I don't know what the original code snippet is like. In any case: I think something went wrong during the copy/paste process, as I don't think your code snippet compiles in its current state.
In any case: as far as I know the AF-methods (the AF stands for Adobe Forms) may not be present in every viewer, and as far as I know Adobe didn't implement a way to subtract values from each other in the AFSimple_Calculate method.
For these two reasons, you may prefer regular JavaScript instead of using a pre-canned function that may or may not be pre-canned.
This regular JavaScript may look like this:
var total1 = this.getField("total1");
var total2 = this.getField("total2");
var subtr = this.getField("difference");
subtr.value = total1.value - total2.value;
I'm not sure if that answers your question. Maybe you just want:
var total1 = this.getField("total1");
var total2 = this.getField("total2");
var namefield = total1.value - total2.value;
You can put these lines inside a String using the right escape characters and replacing the newlines by spaces or newline characters.
Of course, you need to trigger this code somewhere. Below you'll find an example that puts the negative value of the content of a value1 field into a value2 field.
public static void main(String[] args) throws IOException, DocumentException {
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("js.pdf"));
document.open();
writer.addJavaScript("function makeNegative() { this.getField('value2').value = -(this.getField('value1').value); } ");
Rectangle rect1 = new Rectangle(40, 740, 200, 756);
TextField value = new TextField(writer, rect1, "value1");
value.setBorderColor(GrayColor.GRAYBLACK);
value.setBorderWidth(0.5f);
PdfFormField field = value.getTextField();
field.setAdditionalActions(PdfName.BL, PdfAction.javaScript("makeNegative();", writer));
writer.addAnnotation(field);
Rectangle rect2 = new Rectangle(40, 710, 200, 726);
TextField neg = new TextField(writer, rect2, "value2");
neg.setBorderColor(GrayColor.GRAYBLACK);
neg.setBorderWidth(0.5f);
writer.addAnnotation(neg.getTextField());
document.close();
}
Note that I used a Blur action. This means the method will be triggered as soon as you select another field after filling out the value1 field.
I am having to pickup from where someone in the business left off many years ago with an aging texting system.
It was built using ASP classic and sends a string to an API that then texts out, all this is neither here nor there. The problem i have is no JS experience, I am am a SQL Developer and did a little bit of ASP Classic (VBScript) years ago.
This piece of JScript picks up information from several form boxes and then places them in a string which is then passed to variable on a processing page to text out. The fields 'QValue, Indemnity and Excess' are all numeric. The Cover is text and it is replacing the cover text with 'NaN' now I understand this is for 'Not A Number' well that is exactly what it is, not a number but I want the text string.
Here is the snippet of code in question:
<script type="text/javascript">
function changeMessageText()
{
var messagetxt = document.getElementById('message').value
var QValue = document.getElementById('QValue').value
var Cover = document.getElementById('Cover').value
var Excess = document.getElementById('Excess').value
var Indem = document.getElementById('Indemnity').value
var messagetxt=messagetxt.replace("[QValue]", + QValue)
var messagetxt=messagetxt.replace("[Cover]", + Cover2)
var messagetxt=messagetxt.replace("[Excess]", + Excess)
var messagetxt=messagetxt.replace("[Indem]", + Indem)
document.getElementById('messageText').innerHTML = messagetxt;
}
</script>
Cheers.
When you do string.replace(searchvalue,newvalue), there is no need of + before the newValue
var messagetxt=messagetxt.replace("[QValue]", QValue)
//cover or cover2 whichever appropriate
var messagetxt=messagetxt.replace("[Cover]", Cover)
var messagetxt=messagetxt.replace("[Excess]", Excess)
var messagetxt=messagetxt.replace("[Indem]", Indem)
Is it normal that you use Cover2 in the replace where you read the input value and store it in the Cover variable ?
Those are two different variables and from the code you provided, we can only assume that Cover2 is initialized with NaN (which might not be the case, it can be copy/paste error).
Here is how you do it:
var messagetxt = document.getElementById('message').value;
var QValue = document.getElementById('QValue').value
var Cover = document.getElementById('Cover').value
var messagetxt=messagetxt.replace("[QValue]", QValue)
var messagetxt=messagetxt.replace("[Cover]", Cover)
document.getElementById('messagetxt').innerHTML = messagetxt;
Here is a working example of this: http://jsfiddle.net/F24cr/
Enjoy