javascript - show number in UI side without exponential - javascript

I have a data which returns 0.00000000090 from api but in UI side it looks like '9e-10'
I want to show data as 0.00000000090.
My input field is as follows:
<input type="number"
ng-model="model.data"
name="name"
id="id"
min="0"
max="10"
required>
I can do this with javascript like this:
let a = 0.00000000090
a.toFixed(11)
Output -> '0.00000000090'
but after toFixed it shows as 0 because value is string now and my input type must be number.
Can I solve this with html? or any suggestions other than toFixed()?

It seems to be working fine in my example. I've added a step to be 0.000something1 so you could also click the little arrow. Also made an attempt of keeping the display in the decimal format.
number = 0.00000000090
id.value = number.toFixed(11)
id.addEventListener('change', function(ev) {
this.value = (+this.value).toFixed(11)
})
<input type="number" style="width:200px" id="id" min="0" max="10" step="0.00000000001" required>

Related

Force number input to have two decimal places and ONLY two

How can I format the following input for a price to be forced to have two decimal places and ensure that it allows only two places?
So, for example, if the value is '1', it will be changed to '1.00' automatically, and '1.111' will be changed to '1.11'.
I've already tried step="0.01", but this won't work.
JSFiddle: https://jsfiddle.net/eub68raq/.
HTML:
<input data-number="Quantity must be a number" data-required="Unit price required" min="0" step="0.01" id="unitPrice" value="" type="number" name="unitPrice" placeholder="Unit Price"/>
JS I've tried:-
var number = $('input#unitPrice').val();
$('input#unitPrice').innerHTML = parseFloat(Math.round(number * 100) / 100).toFixed(2);
You can do it like below:-
$(document).ready(function(){
$('input#unitPrice').blur(function(){
var num = parseFloat($(this).val());
var cleanNum = num.toFixed(2);
$(this).val(cleanNum);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input data-number="Quantity must be a number" data-required="Unit price required" min="0" step="0.01" id="unitPrice" value="" type="number" name="unitPrice" placeholder="Unit Price"/>
Try this:
parseFloat(number.toFixed(2));
Using your code for rounding, the thing you want could look like this:
$(document).ready(function(){
$('input#unitPrice').change(function(){
$(this).val(parseFloat(Math.round($(this).val() * 100) / 100).toFixed(2));
});
});
Using keyup for this isn't very lucky choice because the user will not be able to change the input value. As soon as he writes something it will be changed to 2 decimal places. If he tries to delete a digit it will be put back.
If you want a keyup behavior, then correcting the value will have to happen with a delay (by using setInterval for example).

Input element that allowes only number with decimals, with AngularJS

I'm trying to create an input element that:
Holds a number (string or actual number doesn't matter).
You shall not be able to enter anything else but numbers and a dot(.).
You are allowed to enter two decimals.
If no decimals are entered, two decimals (i.e. .00) shall be added to the number when leaving the input element (on-blur).
I'm working with AngularJS (1.2) and watch $valid and $invalid on the containing form.
The input is valid when the value is a number with two decimals and the value is larger than 0.
I have tried to use:
<input ng-model="price" type="number" ng-blur="addDecimals()"/>
$scope.addDecimals = function(){
$scope.price = $scope.price.toFixed(2);
}
But then I can't add zeroes as decimals (.00). As toFixed() returns a string, the value is not allowed in the input and it becomes empty.
I have also tried to use
<input type="text" ng-model="price" ng-blur="addDecimals()" ng-change="changed()" />
$scope.changed = function(){
// removes all charachters but numbers and one dot (.);
// examples:
// if value is '1a.t9' it will be changed to '1.9'
// if value is 'qwe' it will be changed to ''
// if value is 4 it will not be changed.
$scope.price = removeAllCharsButNumbersAndDot($scope.price);
}
$scope.addDecimals = function(){
if(parseFloat($scope.price) > 0)
$scope.price = $scope.price.toFixed(2);
else
$scope.price = "";
}
With this solution [form].$valid will be set to true if the value '0' is entered. [form].$valid will be set to false only when the user leaves the input element (on-blur) which is kind of ugly.
I have tried to use ng-pattern="/^\s*(?=.[1-9])\d(?:.\d{1,2})?\s*$/", but then ng-change will not fire.
You can use https://github.com/angular-ui/ui-validate. Ui-validate is great for this. Example:
<input type="number" ng-model="priceModel" ui-validate=" 'checkPriceModel($value)' ">
//Controller:
$scope.checkPriceModel = function(value){
return value <= 0;
}
<form name="theForm" id="theForm">
<input ng-change="changed()" id="priceId" type="number" min="1" name="priceName" ng-model="priceModel" required />
</form>
is the easiest (without extra modules)
If i am getting it right, you can try following
<form name="appTest">
<div
ng-class="{ 'has-error': appTest.app.$touched && appTest.app.$invalid }">
<input type="text" ng-model="vm.text" name="app" ng-pattern={define your pattern}>
</select>
</div>
If its invalid, 'has-error' class will get applied.
You don't need ng-change for this. You can just rewrite your html like this.
<form name="theForm" id="theForm">
<input id="priceId" type="number"
name="priceName" ng-model="priceModel" required min="0" />
<span class="error" ng-show="theForm.priceName.$error.number">
Not valid number!
</span>
</form>
You can read more about it here: https://docs.angularjs.org/api/ng/input/input%5Bnumber%5D

javascript get datepicker start or end value of attribute

<div class="input-daterange input-group" id="datepicker'">
<input type="text" class="input-sm form-control" name="start" />
<span class="input-group-addon">to</span>
<input type="text" class="input-sm form-control" name="end" />
</div>
I know the method goes something like this:
datestart = $("#datepicker").find("input").val();
However this returns 2 different value (Only showing the first one regardless what I do), how do I go about getting just the start or the end of the value?
I was trying something like this:
datestart = $("#datepicker2").find("input").attributes['name'=start].val();
Obviously that doesn't work... Can anyone shine some light on this issue?
You almost got it right:
datestart = $("#datepicker").find("input[name='start']").val();
dateend = $("#datepicker").find("input[name='end']").val();
or better yet:
datestart = $("#datepicker input[name='start']").val();
you can write the following to get the first value
$("input[name=start]").val();
to get the second value use
$("input[name=end]").val();

Why is a HTML form field showing the calculations in the output field

I've created a basic profit calculator which is pretty much working fine. My issue is that every time I enter a number into each of the relevant fields, you can see the workings out in the "Total profit" field. It first tells me my entry is NaN, then -infinity, and then shows the workings. Once I click on my calculate button, I am then finally displayed with the correct number.
For this post I am not concerned with why it is producing the NaN (not a number), but why am I seeing it populated in the field in the first place. I want this field to remain blank until I click Calculate, and then see the resulting number. I suspect it's to do with my JavaScript code but I am a complete newbie - and very stuck.
Your thoughts are most appreciative.
<form id="profitCalculator" action="" class="dark-matter">
<h1>Profit Calculator</h1>
<fieldset>
<p><label>Case Cost:<br />£
<input name="casecost" type="text" value="" size="14" maxlength="8" /></label></p>
<p><label>Units per case:<br /> <input name="packs" type="text" value="1" size="14" maxlength="8" /></label></p>
<p><label>Sell price:<br /> £ <input name="sell_price" type="text" value="" size="14" maxlength="8" /></label></p>
<p><input type="button" class="button" OnClick="Circle_calc(this.form);" value="Calculate"></p>
<p>Total Profit:<br /> £ <input name="profit" type="text" value="0" autocomplete="off" SIZE=14></p>
<p><input type="reset" class="button" value="Reset"></p>
</fieldset>
</form>
And the JavaScript
<script type="text/javascript">
document.getElementById('profitCalculator').onclick = function () {
var casecost = this.elements['casecost'].value || 0;
var packs = this.elements['packs'].value || 0;
var sell_price = this.elements['sell_price'].value || 0;
var profit = (sell_price - casecost) / packs;
this.elements['profit'].value = profit.toFixed(2);
}
</script>
Thank you
You've set a click handler on the form element. Since click events bubble, clicks on the elements inside the form bubble to the form as well. So that's triggering an update to your profit element on anything that any element considers a click.
This diagram from the DOM3 events spec (which has since been folded into the DOM4 spec's events section) may help clarify how bubbling works:
You have a Onclick event on your button that calls Circle_calc function.
Change your function passing the form element as a parameter, and it will work.
Circle_calc = function (form) {
var casecost = form.elements['casecost'].value || 0;
var packs = form.elements['packs'].value || 0;
var sell_price = form.elements['sell_price'].value || 0;
var profit = (sell_price - casecost) / packs;
form.elements['profit'].value = profit.toFixed(2);
}
JsFiddle here

How do I use jQuery to change a field when another field value has changed

I searched and even with answers like JQuery: Change value when value of other input field is changed, I have been unable to figure this out.
I am trying to do some math based on HTML form input. When the user enters numbers in the first and second field, I want it to automatically calculate into the third field to show the total.
My form code is:
<div id="makingARecurringGift">
Enter Recurring Gift Amount: $<input type="number" min="0" name="recurringDonationValue" id="recurringDonationValue" size="15" value="0" /><br />
I would like to make this gift for <input type="number" min="0" max="60" name="numberOfMonths" id="numberOfMonths" size="15" value="0" /> months.<br />
Total Gift Amount of $<input type="number" min="0" value="0" name="totalRecurringDonationValue" />.
</div>
My javascript that I am trying to run is:
function replaceRecurringDonationValue() {
//make our variables so we don't forget
var perDonationValue = 0;
var numberOfMonths = 0;
var TotalRecurringDonationValue = 0;
//give them their correct values
perDonationValue = $("#recurringDonationValue").val();
numberOfMonths = $("#numberOfMonths").val();
//ensure that the maximum number of months is enforced.
if(numberOfMonths > 60) {
alert("Donations can last for a maximum of 60 months.");
$("#numberOfMonths").val(60);
}
TotalRecurringDonationValue = perDonationValue * numberOfMonths;
$("#TotalRecurringDonationValue").val(TotalRecurringDonationValue);
}
$("#recurringDonationValue").change(replaceRecurringDonationValue());
$("#numberOfMonths").change(replaceRecurringDonationValue());
If you would like to view the full main page source code:
http://pastebin.com/aLMqYuxc
and full javascript source is:
http://pastebin.com/FvviPHhj
Sorry if this is a dumb question, thank you all for your assistance. I'm still trying to figure this out.
try changing this:
$("#recurringDonationValue").change(replaceRecurringDonationValue());
to this:
$("#recurringDonationValue").change(function(){
replaceRecurringDonationValue();
});
and this:
$("#numberOfMonths").change(replaceRecurringDonationValue());
to this:
$("#numberOfMonths").change(function(){
replaceRecurringDonationValue()
});
Good shout by Anders,
Even better Combine the two selectors e.g.
$("#recurringDonationValue, #numberOfMonths").change(function(){
replaceRecurringDonationValue();
});
Less Code keep it DRY (Don't Repeat Yourself) :)
Three things...
Change this:
Total Gift Amount of $<input type="number" min="0" value="0" name="totalRecurringDonationValue" />.
To this:
Total Gift Amount of $<input type="number" min="0" value="0" id="totalRecurringDonationValue" />.
Change this:
$("#TotalRecurringDonationValue").val(TotalRecurringDonationValue);
To this:
$("#totalRecurringDonationValue").val(TotalRecurringDonationValue);
And lastly, change this:
$("#recurringDonationValue").change(replaceRecurringDonationValue());
$("#numberOfMonths").change(replaceRecurringDonationValue());
To this:
$("#recurringDonationValue,#numberOfMonths").change(replaceRecurringDonationValue);

Categories

Resources