I have numeric fields on form were users can occasionally type a decimal value with decimal place but no values on one side.
i.e the intended value to be entered can be 5 or 5.00
but occasionally a user can type .5 OR 5.
so in this case if they have left out values before the decimal place, I would like to add/append the value with 0.5 or if they have left out the values after the decimal place I would like to add/append with 5.00
.5 => 0.5
5. => 5.00
Ideally the input value would then be updated onBlur or when user clicks/tabs away from that field or anywhere else on the page. My quick attempt at this is currently as follows (untested)
$('input').on('blur', function () {
var currentValue = $(this).val();
var splitNumber = currentValue.split('.');
var beforeDecimal = splitNumber[0];
var afterDecimal = splitNumber[1];
if (beforeDecimal.length < 1)
{
//add one zero before decimal
}
if (afterDecimal.length < 1)
{
//add two zeros after decimal
}
});
Instead you can just use a combination of parseFloat and toFixed
parseFloat('.5') --> 0.5
parseFloat('5.') --> 5
$('input').on('blur', function() {
let value = this.value;
if(!isNaN(value)) {
let parsedValue = parseFloat(value);
$('.output').text(parsedValue.toFixed(2));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<input type="text" />
<span>Output: </span>
<span class="output">
</span>
Here is an example may help you:
var myNum1 = .5;
var myNum2 = 5.;
function pad(num){
return num.toFixed(2);
}
console.log(pad(myNum1));
console.log(pad(myNum2));
Related
How to validate decimal number with random value from input box using jQuery?
I have sample code below:
$("#actualWeight").on('keyup', function(e) {
if (e.keyCode == 13) {
var actualWeight = $("#actualWeight").val();
var maxGrossWeight = "3.6";
var minGrossWeight = "2.4";
if (actualWeight > maxGrossWeight) {
alert("More than max gross");
} else if (actualWeight < minGrossWeight) {
alert("Lower than min gross");
} else {
alert("Success");
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type="text" id="actualWeight" />
As you can see:
Min Gross = 2.4
Max Gross = 3.6
When I try to input 200, it show me alert Success that should be show me alert More than max gross.
You can see it on this fiddle
.val() is returning the value of input as string. Hence you are comparing string values.
You should set maxGrossWeight and minGrossWeght as float variable and parse the value of input element to float before doing the comparison :
var actualWeight = parseFloat($("#actualWeight").val());
var maxGrossWeight = 3.6;
var minGrossWeight = 2.4;
Working Demo
I am fairly new to javascript. Building a custom javascript calculator to set pricing for some products. There is sometimes a fee that is added. This fee is either a percentage of cost or an actual dollar amount. If it is a percentage, it will have a percentage sign. After researching, came up with the following solution that works only if a dollar amount is entered but not if percentage is entered. Is there a better solution?
<form name="calculator">
<input type="text" name="cost" placeholder="Cost" onkeyup="calculate()">
<input type="text" name="fee" placeholder="fee" onkeyup="calculate()">
<br>
<p>The answer is: </p>
<p id="testAnswer"></p>
</form>
<script type="text/javascript" >
function calculate(){
var a = Number(document.calculator.cost.value);
var b = Number(document.calculator.fee.value);
if(b==""){
var result1= a;
} else {
if (/^\d+(\.\d+)?%$/.test(b)) {
result1 =(1+b)*a;
} else {
var result1 = b+a;
}
}
document.getElementById("testAnswer").innerHTML = result1;
}
</script>
Because you are converting the input to a number with:
var a = Number(document.calculator.cost.value);
var b = Number(document.calculator.fee.value);
Any symbols will cause that conversion to fail and therefore you wouldn't be able to perform your test.
var num = Number("234.50%");
console.log(num); // Not a Number
Instead, before doing the conversion, just simply test for the presence of the symbol with .indexOf which returns -1 when the test can't find a match.
var a = document.getElementById("num1");
a.addEventListener("input", function(){
console.clear();
// Always trim leading or trailing spaces from user input
var input = a.value.trim();
var unit = null;
if(input.indexOf("%") > -1){
unit = "Percent";
} else if(input.indexOf("$") > -1) {
unit = "Dollar";
}
console.log(unit); // null until % or $ is entered
// Now that you know what the unit is,
// you can convert to a number. Use parseInt()
// or parseFloat() for this
var inputNum = parseInt(input, 10);
console.log(typeof inputNum, inputNum);
});
<input type="text" id="num1">
Having said all of that, I agree with the comments that a better way to handle this is by not asking the user to input the unit at all and just provide radio buttons:
var a = document.getElementById("num1");
// Set up click event for radio buttons that enables number input
Array.prototype.slice.call(document.querySelectorAll("input[name='unit']")).forEach(function(btn){
btn.addEventListener("click", function(){
a.removeAttribute("disabled");
});
});
a.addEventListener("input", function(){
console.clear();
// Always trim leading or trailing spaces from user input
var input = a.value.trim();
// Just get the value of the selected radio button
var unit = document.querySelector("input[name='unit']:checked").value;
console.log(unit); // null until % or $ is entered
// Now that you know what the unit is,
// you can convert to a number. Use parseInt()
// or parseFloat() for this
var inputNum = parseInt(input, 10);
console.log(typeof inputNum, inputNum);
});
<!-- If you expect only digits, you can use a number type -->
<input type="radio" name="unit" value="%">%
<input type="radio" name="unit" value="$">$
<input type="number" id="num1" disabled>
Hi I wrote something JQ but i'm not sure is correct :) so would like you to help me figure out how
1.When the user clicks the button (Show results)
2.the two figures are added together and the result is displayed in the span # result
3.check on user input, as a warning, if there is no number entered into the text boxes
only pure jQuery please :)
Thank you in advance for your help.
http://jsfiddle.net/4ke8k5vp/
<body>
<div id="wrapper">
<p>
<input type="text" id="num1" placeholder="Enter a number" value="" />
+
<input type="text" id="num2" placeholder="Enter a number more" value="" />
=
<span class="alert" id="result"></span>
</p>
<input type="button" value="Show results" />
</div>
$(document).ready(function () {
var num1 = $('#num1');
var num2 = $('#num2');
var total = num1 + num2;
$(":button").click(function () {
$("span").html();
});
});
$(document).ready(function () {
var num1 = $('#num1');
var num2 = $('#num2');
$(":button").click(function () {
// Update the total each time the button is clicked.
// Use `parseInt` to convert the string to an integer. Add them.
var total = parseInt(num1.val(), 10) + parseInt(num2.val(), 10);
// Pass the total to the html
$("span").html(total);
});
});
There are a couple of other things you could do to optimize your code, such as adding IDs to the button and the span, but that's outside of your question.
In you javascript you need to cast $('#num1') and $('#num2') to int or float with parseInt() or parseFloat() before adding them.
Also, in your html, the input type should be number, not text.
The whole javascript funtion should be more like this
$(":button").click(function () {
var num1 = $('#num1').val();
var num2 = $('#num2').val();
if (num1 == "" or num2 == "") alert("Please fill both inputs");
else {
var total = parseInt(num1) + parseInt(num2);
$("span").text(total);
}
}
Here is a fiddle: http://jsfiddle.net/Lon5wp7t/
I broke this down for you so you could hopefully learn from the code! The end of this post will give you what you want, but I've gone through to illustrate how we get to that point!
$(document).ready(function () {
// do whatever
});
The above part of the code tells the computer to work what's between the brackets when the document is loaded
$(":button").click(function () {
// do whatever
});
The above adds what's called an "Event Listener" to anything labeled as a button, when that event is triggered it works whatever is between the brackets. In this case it is the "click" event.
You were correct on putting these two together, like so:
$(document).ready(function () {
$(":button").click(function () {
// do whatever
});
});
So what we have so far is that, when the document is loaded, the script adds an event listener to anything labeled button. It doesn't do anything(you'll notice the "//do whatever" is just a comment) but we can certainly fix that.
On click we want the values to be pulled from the input boxes.
$(document).ready(function () {
$(":button").click(function () {
var num1 = $('#num1').val();
var num2 = $('#num2').val();
});
});
Great! Now when the button is clicked, it pulls the input and puts it into 2 variables, num1 and num2. However, when you pull the input you have to realize that what you are pulling from the input boxes are STRINGS. Strings are not recognized as being able to be added. If num1 was equal to 2 and num2 was equal to 3, when you added them together instead of "5" you would get "23". They are concatenated and not computed for a sum. To change that we have to change the input from STRINGS to INTEGERS. We can do this by using the function parseInt() - which will read a string and return an integer.
$(document).ready(function () {
$(":button").click(function () {
var num1 = $('#num1').val();
var num2 = $('#num2').val();
var total = parseInt(num1) + parseInt(num2);
});
});
Finally we have a total, all we have left to do is put it into the span tag!
$(document).ready(function () {
$(":button").click(function () {
var num1 = $('#num1').val();
var num2 = $('#num2').val();
var total = parseInt(num1) + parseInt(num2);
$("span").html(total);
});
});
I have a simple text box and I am entering number value to this.And i want to format the number value to two decimal places and commas at appropriate place.Like If i enter the 10 in the text box and after pressing entering or leaving textbox it should be converted into 10.00. and if i enter 1000 in the textbox and after pressing or entering it should be converted into 1,000.00 Please tell me if there exist any possibility to do this using javascript
<input type="text" name="one" class="currency">
<script>
$('.currency').live('keydown', function(e) {
var key = e.keyCode || e.which;
if (key== 9 || key == 13) {
e.preventDefault();
if( isNaN( parseFloat( this.value ) ) ) return;
this.value = parseFloat(this.value).toFixed(2);
// call custom function here
}
});
</script>
This code will return output as 1000.00
But i need period and commas in their appropriate place
var price = 34523453.345
price.toLocaleString()
O/P "34,523,453.345"
You can use numeral.js (http://numeraljs.com/) to do the job.
Example code:
var string = numeral(1000).format('0,0.00');
// output is 1,000.00
Something like this should do it:
<script type="text/javascript">
function makeCurrency(val){
val = parseFloat(val).toFixed(2);
while (/(\d+)(\d{3})/.test(val.toString())){
val = val.toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2');
}
return val;
}
alert(makeCurrency(12743.7512)); // 12,743.75
alert(makeCurrency(12743)); // 12,743.00
alert(makeCurrency(12743.7)); // 12,743.70
alert(makeCurrency(1274340984893.1)); // 1,274,340,984,893.10
</script>
So you can just copy the function and replace this.value = parseFloat(this.value).toFixed(2); with this.value = makeCurrency(this.value);
Originally from add commas to a number in jQuery
I have an input field which is limited to 6 characters. How can I validate my input field so that a user can't put more than one decimal point (i.e. 19..12), plus it can only be to two decimal places as well (i.e. 19.123)?
This is my input field
<input type="text" name="amount" id="amount" maxlength="6" autocomplete="off"/><span class="paymentalert" style="color:red;"></span>
Here is my validation script.
$(function(){
$("#amount").keypress( function(e) {
var chr = String.fromCharCode(e.which);
if (".1234567890NOABC".indexOf(chr) < 0)
return false;
});
});
$("#amount").blur(function() {
var amount = parseFloat($(this).val());
if (amount) {
if (amount < 40 || amount > 200) {
$("span.paymentalert").html("Your payment must be between £40 and £200");
} else {
$("span.paymentalert").html("");
}
} else {
$("span.paymentalert").html("Your payment must be a number");
}
});
Jonah
This should do :
var ok = /^\d*\.?\d{0,2}$/.test(input);
(if I correctly understood that you don't want more than 2 digits after the dot)
The code thus would be :
$("#amount").blur(function() {
var input = $(this).val();
if (/^\d*\.?\d{0,2}$/.test(input)) {
var amount = parseFloat(input);
if (amount < 40 || amount > 200) {
$("span.paymentalert").html("Your payment must be between £40 and £200");
} else {
$("span.paymentalert").html("");
}
} else {
$("span.paymentalert").html("Your payment must be a number");
}
});
Assuming that:
There MUST have 2 digits after a decimal point, and
There must be at least 2 digits before the decimal point, but no more than 3 digits
The code you would use to match it would be:
var value = $(this).val;
value.match(/^\d{2,3}(\.\d{2})?$/i);
It would be much easier if you used the Masked Input Plugin for jQuery.