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).
Related
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>
$(document).on("change","#noofpack",function(){
count = $(this).val();
for(i=1;i<=count;i++){
$("#packageDiv").html('<input type="text" class="form-control" name="unit_price[]" placeholder="Unit Price" required="">');
}
});
I want to show multiple input fields onchange noofpack if count is 3 then it must show three input fields but what happen here when I change noofpack then it show only 1 input fields. So, How can I do this? Please help me.
Thank You
$(document).on("change","#noofpack",function(){
count = $(this).val();
$("#packageDiv").html(""); // First empty the packageDiv
for(i=1;i<=count;i++){
// Append more instead oh HTML
$("#packageDiv").append('<input type="text" class="form-control" name="unit_price[]" placeholder="Unit Price" required="">');
}
});
This is my textbox that I have:
This is the code for it :
<!-- Preferred credit limit -->
<div class="signup-card-section">
<h2 class="accordion-header boldtext">Tell Us Your Preferred Credit Limit</h2>
<div class="column-control no-padding twelve colgrid">
<fieldset>
<div class="row">
<p class="text-red">(Choose one)</p>
<p>My Preferred Credit Limit<span class="text-red">*</span></p>
<br>
<input type="radio" name="prefcreditlimit" checked="checked" value="yesprefcreditlimit" id="yesprefcreditlimit">
<span class="radiotextdeco">S$</span> <input type="text" class="input numeric-only nodecimal width30" name="prefcreditlimitval" id="prefcreditlimit" min="100"> <span style="font-size:12px;"> (Must be in multiples of 00’ and a minimum of S$100)</span><br><br>
<input type="radio" name="prefcreditlimit" checked="checked" value="noprefcreditlimit"> <span class="radiotextdeco">I dont have a preferred credit limit and agree to any credit limit determined</span><br><br>
<p><strong>Note:</strong> Principal applicant and Suplementary applicant will be granted the preferred credit limit of any limit determined by the bank, whichever is lower.</p>
</div>
</fieldset>
</div>
</div>
Error message to appear if value key in is not in multiples of 00’ or minimum of S$100: “Your Preferred Credit Limit must be in multiple of 00’ and a minimum of S$100.
Since I set the min value to 100. There's an error message appear when user enters less 100. The problem is now, I'm not sure how to check for the validation of 00'
Any help would be appreciated.
Use <input type="number"> along with the min and step attributes:
<input type="number" name="prefcreditlimitval" min="100" step="100">
If the user enters a value lower than the min or something that isn't a multiple of step, the browser's validation will prevent the form from being submitted. In browsers that don't support validation, you can use a polyfill (like this one).
You can test out the validation (though SO doesn't allow forms to run):
input:invalid {
border-color: red;
}
Input multiples of 100<br><br>
<input type="number" name="test" min="100" step="100">
Input tag also has 'pattern' attribute, where you can specify Regex pattern to check input.
So something like
<input type="text" class="input numeric-only nodecimal width30" name="prefcreditlimitval" id="prefcreditlimit" min="100" pattern="\d+00$">
should work!
Some info about input's pattern attr
As mentioned in other answers, you may use min and step attributes to limit value of input field. But these attributes were introduced as a part of HTML 5 standards and it is not supported in all browsers yet.
A generic solution using jQuery/JS to check input value and give error message if it does not meet your requirements can be written as follows.
function validate() {
var value = $("#prefcreditlimit").val();
if (isNaN(value) || value < 100 || value % 100 != 0) {
alert("Please provide a valid input");
$("#prefcreditlimit").val("");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="radiotextdeco">S$</span>
<input type="text" class="input numeric-only nodecimal width30" name="prefcreditlimitval" id="prefcreditlimit" min="100" onblur="validate()"> <span style="font-size:12px;"> (Must be in multiples of 00’ and a minimum of S$100)</span>
You could add some validation in Javascript, checking whether the input is indeed a number, if so then check if it's also at least 100 and if so, check if the input is a multitude of 100. You can do it like this:
var val = parseInt($("#prefcreditlimit").val(), 10);
if (isNaN(val))
{
// ERROR; NOT A NUMBER
}
else if (val < 100)
{
// ERROR; VALUE IS LOWER THAN 100
}
else if (val % 100 !== 0)
{
// ERROR; VALUE IS NOT A MULTITUDE OF 100
}
It seems you want the value to be greater than 100 and a multiple of 100. Seeing as you have tagged the question with jQuery I have done a jQuery example for you.
I am listening for changes on the textfield using .change().
jQuery("#prefcreditlimit").change(function () { ... });
I am using jQuery(this).val(); or jQuery("#prefcreditlimit").val(); to get the current value of the textfield .val()
From your comments, I have updated to first check that the radio button is checked first using !jQuery("#yesprefcreditlimit").is(':checked') which says if the checkbox is not checked.
Then I use simple logic checks first checking if the value is a number isNaN(value) then if value < 100 is less than 100. Then if value % 100 > 0 if the modulus of the value is greater than 100.
There definitely a lot more you could go here, and a lot of different ways you could do this, this is just one way. For example you might not want the change part of this and instead do the validation on the submit of the form.
Note: In the stack snippet you need to click out of the textbox for the change event to be triggered.
jQuery(function () {
jQuery("#prefcreditlimit").change(function () {
var value = jQuery(this).val();
if(!jQuery("#yesprefcreditlimit").is(':checked')) {
jQuery("#warning").text("");
return;
}
if(isNaN(value)) {
jQuery("#warning").text("Value is not a number.");
return;
}
if(value < 100) {
jQuery("#warning").text("Value is less than 100");
return;
}
if(value % 100 > 0) {
jQuery("#warning").text("Value needs to be a multiple of 100");
return;
}
jQuery("#warning").text("Value: " + value + " is Okay!");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>My Preferred Credit Limit<span class="text-red">*</span></p>
<br>
<input type="radio" name="prefcreditlimit" checked="checked" value="yesprefcreditlimit" id="yesprefcreditlimit">
<span class="radiotextdeco">S$</span> <input type="text" name="prefcreditlimitval" id="prefcreditlimit" min="100"> <span style="font-size:12px;"> (Must be in multiples of 00’ and a minimum of S$100)</span><br><br>
<input type="radio" name="prefcreditlimit" checked="checked" value="noprefcreditlimit"> <span class="radiotextdeco">I dont have a preferred credit limit and agree to any credit limit determined</span><br><br>
<p id="warning"></p>
If you have no problem using input type number you can use, step attribute
step = "any" or positive floating-point number NEW specifies the value granularity of the element’s value.
If step is not explicitly included, the value of step defaults to 1, as if it were included with step="1" (or step="100" in the case of type="time"), even if the default value or min value is a float.
<input type="number" class="input numeric-only nodecimal width30" name="prefcreditlimitval" id="prefcreditlimit" min="100" step="100">
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
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);