Obtain numbers from a field and process them - javascript

I have a field which obtains it input through a list of links associated with numbers. (Similar to a calculator but without operators). I want to retrieve these numbers and put them through a function which divides them by 12. (A conversion from feet to inches).
First I have a list of jQuery click functions like this:
$('#a0').click(function(){
writeInput(input, one); // var one = 1;
});
Next I have the function "write Input" (This is where the numbers are displayed on a "screen")
function writeInput(field, str){
$input = $(field);
var text = $input.val($input.val() + str);
$input.text(text);
convert(text);
}
And lastly I have a function which is supposed to divide the number inputted by 12
function convert(input){
var divide = (input / 12);
$("#output").html(divide); //output is a paragraph where the number is displayed
}
When I run my code I am getting NAN output where the number should be. I have tried parseInt() and other tricks. But the closest I have come to something correct is when I got [object] [object] output.
Any help would be appreciated. Thanks!

In your code text is a jQuery object, you are using val as setter which returns a jQuery object, you should use val/text method as a getter for retrieving updated value.
function writeInput(field, str){
var text = $(field).val(function(i, v){
return v + str;
}).text(function(i, t){
return t + str
}).val();
convert(text);
}

Related

Searching keywords in JavaScript

Here's an example of the customer codes:
C000000123
C000000456
If I input C123 in the search box, "C000000123" will automatically display.
9 numbers are fixed.
Please help me, a short sample was shown to me but I don't get it.
function test(key, num, digit) {
let retStr;
xxxx (condition)
retun retStr;
}
here's an elaboration:
**
input:123
output:A00000123
input:1
output:A00000001
input:99999
output:A00099999
**
here's the detailed demand:
Since it takes time and effort to enter the management number “alphabet + numeric value 9 digits” on the search screen, when the alphabetic number and the number excluding the leading 0 are entered, it is automatically complemented so that it becomes 9 padded with zeros.
sorry i'm very very new to programming in javascript
Try this:
May be what you want...
Please test it and tell if its what you want.
function getOutput(input){
var str=input.substring(1,input.length);
var padd0=9-str.length;
var zr="000000000";
var zrsub=zr.substring(0,padd0);
var output=input[0]+zrsub+""+str;
return output;
}
//Example: Call it like (NB any letter can be used):
getOutput("C123"); //or
getOutput("D123");
You can use .endsWith in js which takes a string and a search string and returns true if the specified string ends with the search string.
This function takes an array of customer ids and a search string and returns the matching customer id
function searchCustomer(customers, searchString) {
return customers.find(customer => customer.endsWith(searchString));
}
searchCustomer(['C000000123', 'C000000456'], 123); // "C000000123"
searchCustomer(['C000000123', 'C000000456'], 456); // "C000000456"
searchCustomer(['C000000123', 'C000000456', 'A00000001'], 1); //"A00000001"

Convert specific value in a form to avoid 1.0 does not equal 1

I am currently trying to take all changes made to a form and put it into a JSON. If there are no changes than the JSON is empty. The form contains values that are strings, ints, and floats. So, I cannot cast them all as a specific type.
This wasn't an issue until I ran into the result form the console.log statement batchsize:string 1.0 does not equal string 1. Obviously this is correct in saying the two strings are not equal, but I am having trouble with finding a way that allows me to compare them without this being an issue. Does anyone have any advice
function getChanges()
{
//Get All User made changes form the website
var returnJSON = "{ ";
$('#form *').filter(' input:not([type="submit"])').each(function(){
var current = this.value;
var original = this.getAttribute('value')
var id = $(this).attr('id');
if((id!=="prod")&&(id!=="prodamt")&&(id!=="subtotal")&&(id!=="matlamt")&&(id!=="tax")&&(id!=="total")&&(id!=="matl")&&(id!=="prod-detail-formula-price")&&(id!=="prod-detail-formula-taxable")) //this ones for you zoe
if(current !== original)
{
returnJSON += '"'+id+'" : { "original":"'+original+'", "modified":"'+current+'"},';
console.log(id+":"+typeof original+ original +" does not equal " +typeof current+current);
}
});
returnJSON = returnJSON.substr(0, returnJSON.length-1);
returnJSON += '}';
return returnJSON;
}
use $.isNumeric() and if both are numeric check are they equal as a numbers using parseFloat or parseInt to convert to numeric

jquery comparing 2 integers

My submit click function is as below.
aAmt is a $ field like for eg. $45.00
a_amount is always 10000.
I am converting a_amount to $ in displayCurrencyFormat function.
I am then converting both to parseInt and doing >= comaprison and it fails. Even though aAmt is > $10000 and conition should display alert it doesnt.
$("#submitId").click(function () {
var aAmt = $("#aAmt").val();
var a_amount = "${dAmt}";
a_amount = displayCurrencyFormat(a_amount);
var pLen = $("#pOd").val();
if ((parseInt(aAmt) >= parseInt(a_amount)) && (pLen.length == 0)) {
$('#pDiv').text('Please provide a password');
$("#pOd").focus();
return false;
}
...//
});
function displayCurrencyFormat(a_amount)
{
//convert amount to currency format
var nbrAmt = Number(a_amount.replace(/[^0-9\.]+/g,""));
var fmtAmt = '$' + nbrAmt.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
return fmtAmt;
}
You should convert it into an integer-like data first, and then you can compare them.
The currency formatted input are considered as not a number format so comparing them are something like String to String comparison, not Number to Number like what you want to achieve.
Refrence link: How to convert a currency string to a double with jQuery or Javascript?
Do you know that parseInt('$10000') actually giving you "NaN"?
And as i can see here you are trying to compare integer and string...
Just try to alert aAmt and a_amount variables before you compare them and you will see what is actually going on...

how to get value of an input box in html and do operations on it

I was testing a simple code to:
Get value of an input box
Do Mathematical operations on it...
My Code:
setInterval(function(){var a=document.getElementById("myInputBox").value;var b=a+1;a.value=b;},1000);
I am trying to add 1 to the value of that input box, every 1 second.
For example, if the box has value 1 ,then after 1 second it should become 2,....and so on.....
But it gets joined with the box's value, like 11 instead of 2.
Why is that?
Try with full code & demo:
get value from inputbox is a string, so it can't calculate mathematically. so, at first convert string to numeric by using function parseInt and then calculate and put into box.
setInterval(function() {
var box = document.getElementById("myInputBox");
var r = parseInt(box.value, 10) + 1;
box.value = r;
}, 1000);
<input type="text" id="myInputBox" value="1" />
var b = parseInt(a) + 1;
a is a string, so the + is interpreted as string concatenation by default. To fix, pass a to parseInt because it returns a type integer. Now the + becomes a math operator.
Extra Credit:
var b = parseInt(a, 10) + 1;
For an extra measure of integrity, pass the second (radix) argument, ensuring base 10 is used to determine the return integer value.

JavaScript function to add two numbers is not working right

My code in HTML takes a user input number in, and it does a calculation and then displays the output. The user chosen input is put into a formula and the result of the formula is added to the user input number, but when it adds the two number together it's adding a decimal spot.
For example, if the number 11 is chosen, the result of Rchange is 0.22, so .22 is then added 11 to be 11.22 for newResistance, but instead it is displaying the value as 110.22 instead.
function calc(form) {
if (isNaN(form.resistance.value)) {
alert("Error in input");
return false;
}
if (form.resistance.value.length > 32) {
alert("Error in input");
return false;
}
var Rchange = .01 * 2 * form.resistance.value;
var newResistance = (form.resistance.value + Rchange);
document.getElementById("newResistance").innerHTML = chopTo4(newResistance);
}
function chopTo4(raw) {
strRaw = raw.toString();
if (strRaw.length - strRaw.indexOf("0") > 4) strRaw = strRaw.substring(0, strRaw.indexOf("0") + 5);
return strRaw;
}
HTML DOM element properties are always strings. You need to convert them to numbers in your usage.
parseInt(form.resistance.value);
parseFloat(form.resistance.value);
+form.resistance.value;
(Any of the three will work; I prefer the first two (use parseInt unless you're looking for a float).)
Try newResistance = +form.resistance.value + Rchange;. This will convert it to a number.
It's because it's treating the values as a string.
form.resistance.value + Rchange are both strings, so it's appending it.
Use the parseInt JavaScript method to get the decimal version.

Categories

Resources