Remove NaN from input field when removing variable - javascript

I'm making a simple calculator and i have a bit of code that i got from a previous question:
$("input[type=text]").keyup(function () {
var number = parseFloat($(this).val());
var inc = parseFloat($(this).attr("inc"));
var newValue = number / inc;
$("input[type=text]").each(function () {
$(this).val(newValue * parseFloat($(this).attr("inc")));
});
});
When i enter a value then delete it the box's equal NaN, i just need to know how to stop it from displaying it and display 0 in its place.
JSFiddle Here

Test if the number if NaN before using it:
var number = parseFloat($(this).val());
if (isNaN(number)) {
number = 0;
}

You can use isNaN(val): to check if its number is illegal.
$("input[type=text]").each(function () {
if(isNaN(newValue * parseFloat($(this).attr("inc"))))
$(this).val(0);
else
$(this).val(newValue * parseFloat($(this).attr("inc")));
});
Working Demo

Test the value using isNaN() this will allow you to alter the output
http://jsfiddle.net/J24yN/153/
newValue * parseFloat($(this).attr("inc"))
if(!isNaN(newValue)){
$(this).val(newValue);
} else {
$(this).val(0);
}

Related

Calculating 2 values from fields but it's not working properly

I am calculating 2 fields on a form with values but it seems in some cases it's not working. Here's my javascript. I am adding $oneTimeCostField and $recurringTotalCostField to get the value into the $totalRetailAmountField. Here's the result I am getting when I add say 1,555.00 + 566.00 = the value is 567.00 (?). Any idea what I'm doing wrong? In some cases it works correctly when the values are lower. Thanks, just stumped
var $recurringCostField = $('#am_attribute_campaign_addon_monthly_cost_value');
var $recurringTotalCostField = $('#am_attribute_campaign_addon_total_monthly_cost_value');
var $totalRetailAmountField = $('#am_oie_string_total_monthly_cost_value');
var $oneTimeCostField = $('#am_attribute_campaign_addon_one_time_cost_value');
function calcVal() {
var num1 = $oneTimeCostField.val();
var num2 = $recurringTotalCostField.val();
var result = parseFloat(num1) + parseFloat(num2);
if (!isNaN(result)) {
$totalRetailAmountField.val(result.toFixed(2));
}
}
calcVal();
$oneTimeCostField.on("keydown keyup", function() {
calcVal();
});
$recurringTotalCostField.on("keydown keyup", function() {
calcVal();
});
You need to remove the commas before parsing:
var result = parseFloat(num1.replace(/,/g, '')) + parseFloat(num2.replace(/,/g, ''));
similiar question on this link
Remove commas from the string using JavaScript
That is because parseFloat() converts the string "1,555.00" to the number 1.
To convert it to a proper floating point number, it needs to include a single dot only.
console.log(parseFloat("1.555"));

Decrease integer working, identical increase integer is not [duplicate]

This question already has answers here:
Why does JavaScript handle the plus and minus operators between strings and numbers differently?
(7 answers)
Closed 5 years ago.
Increase and decrease should add or subtract 0.1 to the current value. They are setup the same. For some reason decrease works (1.0 becomes 0.9, 0.8, etc.) but increase does not (1.0 becomes 1.00.1) as if it's concatenating a string.
I have tried with parseInt and parseFloat with no luck on increase new_value = current_value + 0.1 but decrease does work new_value = current_value - 0.1
I would expect both to either work on not work the way this is setup.
HTML:
<button data-direction="increase">increase</button>
<button data-direction="decrease">decrease</button>
<input value="1.0" />
JS:
$(function() {
var button = $('button');
button.click(function() {
var button = $(this);
var direction = button.data('direction');
var input = $('input');
var current_value = parseFloat( input.val() ).toFixed(1);
var new_value;
if (direction=='increase') {
new_value = current_value + 0.1;
} else {
new_value = current_value - 0.1;
}
input.val(new_value);
});
});
Fiddle:
https://jsfiddle.net/6s6w8fyd/
.toFixed(1) converts the Number into a String.
When adding a number to a string, the number is implicitly converted into a string, thus adding the '0.1' string to the end.
Subtracting doesn’t work on strings so it behaves a little differently: the string will be implicitly converted into a number.
You want to call .toFixed after adding or subtracting.
You're approach for this 'problem' is way too complex and can be brought back to very simple code. First change the values of your data-direction.
<button data-direction="1">increase</button>
<button data-direction="-1">decrease</button>
If you always follow the rule that everything that comes from the view (html) is a string and needs to be cast before any calculation takes place, then your always safe.
Your javascript becomes:
$(function() {
var button = $('button');
var curr_value = 1; // Set it to what you want your starting value to be
button.click(function() {
var button = $(this);
// direction is an integer now: 1 or -1
var direction = parseInt(button.data('direction'));
// Not 'safe' to directly parse it from the input,
// in case someone types in non numeric values.
// Do a check or - even better - make sure non-numeric values can't be
// entered.
var f = $('input');
// check here
var input = parseFloat(f); // input is a number here
// Set the new curr_value
curr_value = curr_value + (input * direction);
input.val(curr_value);
});
});
To be safe with this I would build in checks for the value that is typed in etc... But leave that up to you. Hope it helps...
$(function() {
function decimal(number, boo){
number = parseFloat(number);
return +((boo) ? (number + 0.1):(number - 0.1)).toFixed(1);
}
var input = $('input');
$('button').click(function() {
var direction = $(this).data('direction');
var inputvalue = input.val();
input.val(decimal(inputvalue, direction=="increase"));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button data-direction="increase">increase</button>
<button data-direction="decrease">decrease</button>
<input value="1.0" />

replace each selected value with random letter/number

So I'm wondering how can I for example go over each specific text or number I've set and change them. For example I have:
0000-0000
and I want to replace each 0 with some input I've set. For Example:
1111-1111
I'm trying create random serial code kind of script so I'd just like to start of by how to do that.
Thanks in advance.
Edit: So this is how I would generate the random number or letter, just gotta go trough each zeros to replace them with random value:
jQuery(document).ready(function ($) {
function randomAlphaNumber() {
var values = "abcdefghijklmnopqrstuvwxyz0123456789";
rN = values.charAt(Math.floor(Math.random() * values.length));
return rN;
}
$(".combination").html(randomAlphaNumber());
});
At its simplest I'd suggest:
function randomiseString(str){
var chars = "abcdefghijklmnopqrstuvwxyz0123456789";
var _str = str.replace(/[^-]/g,function(a){
return chars[Math.floor(Math.random() * chars.length)];
});
return _str;
}
$('.combination').text(function(i,t){
return randomiseString(t);
});
JS Fiddle demo.
If you also want to use upper, and lower, case letters:
function randomised(len) {
return Math.floor(Math.random() * len);
}
function randomiseString(str){
var chars = "abcdefghijklmnopqrstuvwxyz0123456789";
var _str = str.replace(/[^-]/g,function(a){
return chars[randomised(chars.length)][randomised(2) == 0 ? 'toUpperCase' : 'toLowerCase']();
});
return _str;
}
$('.combination').text(function(i,t){
return randomiseString(t);
});
JS Fiddle demo.

jQuery/JavaScript: Auto Number Format

Currently, I am using this plugin https://github.com/teamdf/jquery-number to auto-format the number that I entered, but I encountered some problem, when I enter
999999999999999.99 it will round off to 1,000,000,000,000,000.00, I don't need to round off the number that I entered, I only need to format the number using the comma,
I need the exact numbers that I entered, how can I do it? is there any way?
here is my current code:
$(".numeric-total").blur(function () {
var value = $(this).val();
value = $.number(value.replace(/,/g, ""), 2);
$(this).prop('value', value);
});
<script>
jQuery(document).ready(function () {
$(".numeric-total").blur(function () {
var value = $(this).val();
value = value.replace(".", ",");
value = $.number(value.replace(/,/g, ""), 2);
alert(value);
$(this).prop('value', value);
});
});
</script>

Adding characters to string (input field)

I have a text box where the value is the result of a calculation carried out in jQuery. What I would like to do, using jQuery, is to display brackets around the number in the text box if the number is negative.
The number may be used again later so I would then have to remove the brackets so further calculations could be carried out.
Any ideas as to how I could implement this?
Thanks
Zaps
function FormatTextBox(id) {
var txtBox = $(id).val();
//strip bracket to get the number only
txtBox = txtBox.replace("[", "").replace("]", "");
var val = parseFloat(txtBox);
if (val < 0) {
txtBox.val("[" + val + "]");
} else {
txtBox.val(val);
}
return val;
}
First, store your calculation in a variable. You shouldn't be using the DOM to store data (in most cases). This basically eliminates your problem.
Number.prototype.bracketed = function() {
if(this < 0) {
return '[' + -this + ']';
} else {
return '' + this;
}
};
var result = do_calculation();
myTextBox.value = result.bracketed();
// result still holds the original Number value.
If you really want to store the data as the .value of the text input, you can make an unbracketed function as well:
String.prototype.unbracketed = function() {
var parts = this.match(/^\[([0-9]+)\]$|^([0-9]+)$/); // [number] or number
if(parts[1]) { // [number]
return -parseInt(parts[1], 10);
}
if(parts[2]) { // number
return parseInt(parts[2], 10);
}
return NaN;
};
Assuming you might have multiple fields (and you don't want the negative sign):
jQuery('input').each(function(){
if(jQuery(this).val() < 0 ){
jQuery(this).val('['+-1*jQuery(this).val()+']');
}
}
)
Then when you grab the value again, just strip the brackets and multiply by -1 to make it negative.
EDIT:
You can also use jQuery('input').data() to store the original number so you don't have to parse it again. (read more: http://api.jquery.com/data/ )

Categories

Resources