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
Related
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));
I have a single input field where the user can only enter a number between 2 AND 50. Anything above or below is invalid. It also MUST be a numeric value.
What I have so far is this:
$('#searchTimes').click(function() {
if($('#replyNumber').val()<=0) {
alert("Please select a value greater than 0 for number of guests");
$('#replyNumber').focus();
return;
}
if($('#replyNumber').val()>=51) {
alert("Please select a value less than or equal to 50 for number of guests");
$('#replyNumber').focus();
return;
}
if(isNaN($('#replyNumber').val())) {
alert("Please enter a numeric value only");
$('#replyNumber').focus();
return;
}
});
Is there a better more efficient way of writing that ^.
Also ... IF all of those IF statements are not true then I need to perform another function. How can I add that in?
_isValidNumber(number) {
var message;
var isValid;
switch(number){
case number >= 51:
message = "Please select a value less than or equal to 50 for number of guests";
isValid = false;
case number <= 0:
message = "Please select a value greater than 0 for number of guests";
isValid = false;
case isNumeric(number):
var message = "Please enter a numeric value only";
isValid = false;
default:
return true;
}
alert(message);
$('#replyNumber').focus()
return isValid;
}
function isNumeric(num){
return !isNaN(num)
}
var number = $('#replyNumber').val();
var numberIsValid = _isValidNumber(number);
I would try to abstract out duplicate code, like this:
<input id="replyNumber" >
<button id="searchTimes">click</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$('#searchTimes').click(function() {
var val = $('#replyNumber').val()
if(val<=0) showErr("Please select a value greater than 0 for number of guests");
else if(val>=51) showErr("Please select a value less than or equal to 50 for number of guests");
else if(isNaN(val))showErr("Please enter a numeric value only");
});
function showErr(msg){
alert(msg);
$('#replyNumber').focus();
}
</script>
This is what you need :D
$('#searchTimes').on('click',function() {
var do_function = 1;
if (!$.isNumeric($('#replyNumber').val())) {
alert("Please enter a numeric value only");
$('#replyNumber').focus().select();
} else if (+$('#replyNumber').val() < 2) {
alert("Please select a value at least 2 for number of guests");
$('#replyNumber').focus().select();
} else if (+$('#replyNumber').val() > 50) {
alert("Please select a value no more than 50 for number of guests");
$('#replyNumber').focus().select();
} else {
do_function = 0;
}
if (do_function) {
call_some_function();
}
});
Good luck!
Use HTML5 min and max attributes and an input of type number (which covers the numeric part you mentioned). Use rangeOverflow and rangeUnderflow Validity Properties to check your input and present the proper error (or custom error) messages.
Try the below snippet using the following values (null (empty input),1,55) and check the custom error messages created.
function validateInput() {
var txt = "";
if (document.getElementById("inp1").validity.rangeOverflow) {
txt = "Value larger than acceptable!";
}
if (document.getElementById("inp1").validity.rangeUnderflow) {
txt = "Value smaller than acceptable";
}
if (document.getElementById("inp1").validity.valueMissing) {
txt = "Please type a number!";
}
document.getElementById("output").innerHTML = txt;
}
document.getElementById("btn").addEventListener("click", function(){
validateInput();
});
<form>
<input type="number" id="inp1" name="numberInput" min="2" max="50" required>
<button id="btn">go</button>
</form>
<div id="output"></div>
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.
I have 12 fields in a form and I'd like to loop through all these 12 text fields and convert the value in those fields to decimal/currency. These 12 (Jan to Dec) fields are numeric (currency US$) only.
And in the end, show in another field:
txtPendingBalance.value = TotalValue.text - (Sum(Field1..12))
What's the best way doing it? jQuery? pure js?
The following code should do it. "totalbuttonID" should be the ID of the button that is pressed to total the inputs. The inputs that are being totaled need to have the class addToTotal.
$('#totalbuttonID').click(function() {
val total=0.0;
$('.addToTotal').each(function(){
total+=parseFloat($(this).val())
})
$('#txtPendingBalance').val(parseFloat($('#TotalValue').val())-total);
})
Check this Example FIDDLE
$(function() {
$('#btn1').on('click', function() {
var $textboxes = $('.a input[type=text]');
var $balance = $('#totalbalance') ;
var $pending = $('#pendingbalance');
var tot = 0;
$.each($textboxes , function(i){
tot += parseFloat($(this).val());
})
var pending = parseFloat( parseFloat($balance.val()) - tot );
$pending.val( parseFloat(pending).toFixed(2));
});
});