jQuery .val() Not Able to be Converted to Int using parseInt - javascript

I have tried parseInt() to no avail. I still get NaN errors using this code...
$("#belt-length").on("input", function(){
var length = parseInt($("#belt-length").val(), 10);
var width = parseInt($("#belt-width").val(), 10);
if(length > 0 && width > 0) {
var squaremm = length * width;
var square = squaremm / 1000000;
$("#belt-square-meters").html(square.toString() + "m<sup>2</sup>");
} else {
$("#belt-square-meters").html("0.00 m<sup>2</sup>");
};
});
$("#belt-width").on("input", function(){
var length = parseInt($("#belt-length").val(), 10);
var width = parseInt($("#belt-width").val(), 10);
if(length > 0 && width > 0) {
var squaremm = length * width;
var square = squaremm / 1000000;
$("#belt-square-meters").html(square.toString() + "m<sup>2</sup>");
} else {
$("#belt-square-meters").html("0.00 m<sup>2</sup>");
};
});
I have tried converting the fields to type="number". I use the .val() method as it is my understanding that .val() will pull the actual value of the form field and not an object reference to the form field.

1. Of course you can convert .val() result to integert via parseInt. parseInt method accepts string as a first parameter (MDN. parseInt), while .val() returns "the value of the value attribute of the FIRST matched element" (W3Schools. jQuery val() Method) which is string in text-input case (W3Schools. Input Text value Property). So there is no problem with your code and your (length > 0 && width > 0) NaN-protection is pretty common here.
2. I'd recommend do some refactoring. Extract your handlers into a single function and simplify output:
function processInput() {
var length = parseInt($("#belt-length").val(), 10);
var width = parseInt($("#belt-width").val(), 10);
var square = '0.00';
if(length > 0 && width > 0) {
var squaremm = length * width;
square = squaremm / 1000000;
}
$("#belt-square-meters").html(square + "m<sup>2</sup>");
}
$("#belt-length").on("input", processInput);
$("#belt-width").on("input", processInput);
DEMO: https://plnkr.co/edit/D5YcsQGJzqqIUbou0rxI?p=info

Related

How to correctly use values from textboxes in html pls help me

I wanted to use values from textboxes but failed so i tried with constant values and now I am getting a NAN error. I am showing my result in a label btw.
function myFunction() {
var translength = 2400
var transSpacing = 150
var transEndOverhang = 75
var transStartOverhang = 75
var longLength = 6000
var LongSpacing = 150
var LongStartOverhang = 75
var LongEndOverhang = 75
if (transSpacing != 0)
document.getElementById('longAmount').value = ((transLength - transStartOverhang - transEndOverhang) / transSpacing) + 1;
document.getElementById('longAmount').innerHTML = document.getElementById('longAmount').value
if (document.getElementById('longAmount').value > 0 && transStartOverhang + ((document.getElementById('longAmount').value - 1) * transSpacing) + transEndOverhang < transLength)
document.getElementById('longAmount').value = longAmount + 1;
document.getElementById('longAmount').innerHTML = document.getElementById('longAmount').value
}
You're mixing innerHTML and value for the same id. If that id is a textbox you should use .value. Also, to convert strings (the text from the textarea) you can use parseInt() or parseFloat().
// Here you're taking a bunch of variables and sets the textareas value
document.getElementById('longAmount').value = ((transLength - transStartOverhang - transEndOverhang) / transSpacing) + 1;
// Makes no sense (textarea doesn't have a innerHTML)
document.getElementById('longAmount').innerHTML = document.getElementById('longAmount').value;
// document.getElementById('longAmount').value is a string here
if (document.getElementById('longAmount').value > 0 && transStartOverhang + ((document.getElementById('longAmount').value - 1) * transSpacing) + transEndOverhang < transLength)
document.getElementById('longAmount').value = longAmount + 1; // longAmount is undefined.
// Again, makes no sense.
document.getElementById('longAmount').innerHTML = document.getElementById('longAmount').value;

Calculations on formatted text fields

I have a form that will collect various data about properties. The user enters in values to select fields and onBlur, those values are formatted with comma's, dollar signs, and/or percentage signs.
I'm trying to create some real time calculations based on those inputs, but I'm having a hard time getting started on this. I have created a jfiddle page and have been playing around with ideas for the past few hours, but I just cannot seem to get the first calculation working.
I know I need to strip out any characters and have tried parseInt, parseFloat, replace, ect. Just nothing seems to work.
Thank you in advance.
function formatNumber(number, digits, decimalPlaces, withCommas)
{
number = number.toString();
var simpleNumber = '';
// Strips out the dollar sign and commas.
for (var i = 0; i < number.length; ++i)
{
if ("0123456789.".indexOf(number.charAt(i)) >= 0)
simpleNumber += number.charAt(i);
}
number = parseFloat(simpleNumber);
if (isNaN(number)) number = 0;
if (withCommas == null) withCommas = false;
if (digits == 0) digits = 1;
var integerPart = (decimalPlaces > 0 ? Math.floor(number) :
Math.round(number));
var string = "";
for (var i = 0; i < digits || integerPart > 0; ++i)
{
// Insert a comma every three digits.
if (withCommas && string.match(/^\d\d\d/))
string = "," + string;
string = (integerPart % 10) + string;
integerPart = Math.floor(integerPart / 10);
}
if (decimalPlaces > 0)
{
number -= Math.floor(number);
number *= Math.pow(10, decimalPlaces);
string += "." + formatNumber(number, decimalPlaces, 0);
}
return string;
}
function sumCalc() { // function to remove comma and then calculate
var glasf =
document.getElementById('gross_land_sf').value.replace(/,/g, "");
document.getElementById('gross_land_acre').value = formatNumber(glasf/43560);
}
https://jsfiddle.net/vva3x3wu/4/
Is this what you want ? I did some fixes:
https://jsfiddle.net/vva3x3wu/11/
In the link you put in the comment you removed class .cal from the first input, so calculations will not star until you tab from the last input.

Limit numbers after decimal, add 0 if one digit

I'm trying to make a text field so that if there's a number 153.254, that becomes 153.25. And if the field contains 154.2, an extra 0 is added to fill two spots after decimal; 154.20.
toFixed() works great but I don't want the number rounded. Also came across other solutions where if I'm typing in 1.40, then if I move the cursor back after 1, I can't type anything in unless I clear the field and start over.
Is there a simple jQuery way to limit two characters after a decimal, and then if there's only one character after the decimal, add a zero to fill the two character limit?
(The field may receive value from database that's why the second part is required)
Solution Update: For those interested, I put this together to achieve what I wanted (Thanks to answers below and also other questions here on stackoverflow)
$('.number').each(function(){
this.value = parseFloat(this.value).toFixed(3).slice(0, -1);
});
$('.number').keyup(function(){
if($(this).val().indexOf('.')!=-1){
if($(this).val().split(".")[1].length > 2){
if( isNaN( parseFloat( this.value ) ) ) return;
this.value = parseFloat(this.value).toFixed(3).slice(0, -1);
}
}
return this; //for chaining
});
you could do myNumber.toFixed(3).slice(0, -1)
try this:
var num = 153.2
function wacky_round(number, places) {
var h = number.toFixed(2);
var r = number.toFixed(4) * 100;
var r2 = Math.floor(r);
var r3 = r2 / 100;
var r4 = r3.toFixed(2);
var hDiff = number - h;
var r4Diff = number - r3;
var obj = {};
obj[hDiff] = h;
obj[r4Diff] = r4;
if (r4Diff < 0) {
return h;
}
if (hDiff < 0) {
return r4;
}
var ret = Math.min(hDiff, r4Diff);
return obj[ret];
}
alert(wacky_round(num, 2))
How about
function doStuff(num){
var n = Math.floor(num * 100) / 100,
s = n.toString();
// if it's one decimal place, add a trailing zero:
return s.split('.')[1].length === 1 ? (s + '0') : n;
}
console.log(doStuff(1.1), doStuff(1.111)); // 1.10, 1.11
http://jsfiddle.net/NYnS8/

javascript variable > than number

What I am tying to find is:
"if div contains '(a number greater than 1600 x a number greater than 1063)' alert success else alert error"
if (($('div:contains("(/*number greater than 1600*/ x /*number greater than 1063*/)")').length > 0)) {
alert("SUCCESS");
}
else {
alert("ERROR");
}
I thought I could use variables like
var w > 1600
var h > 1063
and then put them in like:
$('div:contains("('+ w + 'x' + h + ')")')
but that doesn't seem to work
Any ideas?
If your goal is to find all matching divs, you have to do a bit more work. Not a lot, but a bit:
var w = 1600;
var h = 1063;
// Find all divs and filter them
var matchingDivs = $("div").filter(function() {
// Does this div's text match the form (1601 x 1064)?
// If so, grab the numbers.
var match = /^\((\d+) x (\d+)\)$/.exec($(this).text());
if (match) {
// Yes, it does, do the numbers fit?
if (parseInt(match[1], 10) > w && // [1] = the first capture group
parseInt(match[2], 10) > h) { // [2] = the second capture group
// Keep this div
return true;
}
}
// Don't keep this div
return false;
});
If a div contains a number and nothing else, you can get it like this:
var num = Number($("#myDiv").text());
Or you can use the somewhat terser unary plus:
var num = +($("#myDiv").text());

Remove Euro Value and money format with JQuery

I already know how to get a value from a label, the problem is that its showing something like
€123,453.28
I need to remove the eurosign and the commas to be able to make a calculation.
Not remove the decimal point of course
$(document).ready(function () {
$("#TxtVatExcluded").keypress(function () {
var invoicedAmmount = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
alert(invoicedAmmount);
if (invoicedAmmount > 0) {
var ammountWithoutVat = $("#TxtVatExcluded").val();
var result = (ammountWithoutVat / invoicedAmmount) * 100;
$("#OutputLabel").html(result + " %");
}
});
});
"€123,453.28".replace(/[^\d.]/g,"") // Replace every non digit char or dot char
// With an empty string.
Live DEMO
So in your code:
var ammountWithoutVat = $("#TxtVatExcluded").val().replace(/[^\d.]/g,"");
var result = (pareseFloat(ammountWithoutVat, 10) / invoicedAmmount) * 100;

Categories