text box decimal format fixing in php - javascript

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

Related

How to detect when a user types a string in an input type number?

I have a form with an input type number. I want to display a message when the user types a string.
When I try to retrieve the value of the input, I always get an empty string.
When I type a number it works fine but not with a string...
I tried with both jQuery and javascript.
var inputVal = $(this).val();
var inputValJs = document.getElementById("myInput").value;
console.log(inputVal); // if 99 => 99 if test => ''
console.log(inputValJs); // if 99 => 99 if test => ''
How should I proceed ?
Input type number only allow you to enter numbers
var inputValJs = document.getElementById("myInput").value;
console.log(inputValJs);
<input type="number" id="myInput" name="tentacles" value ="33">
If you really need an input text you can do the following:
The event input captures the changes in the input text.
var messageElem = document.querySelector('#myMessage');
document.querySelector('#myInput').addEventListener('input', function(e) {
if (this.value === '' || /^[0-9]+$/.test(this.value)) {
messageElem.textContent = "";
} else {
messageElem.textContent = "Only numbers";
}
});
<input type="txt" id='myInput'>
<p id='myMessage'>
Number type input only accept number value.
To retrieve input value, use event listener :
var myValue = '';
document.getElementById("myInput").addEventListener('input', function(e) {
myValue = e.target.value;
console.log(myValue);
});
<input type="number" id="myInput">

jQuery decimal validation with random value not correct

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

"undefined" is appearing for first time during validation on JSP page

I am validating user input where it should accept only 6 digits or OB followed by 8 digits only.
It works very fine for digits but when I enter any alphabet (other than O) for first time it shows "undefined" in the input text box. How to overcome this? I have initialize all variables and tried changing regular expression(/[OB0-9]*/) also but nothing is working.
Here is my jsp code with RegEx:
<input type="text" value="<c:out value='${bookingPathView.extraAANumber}'/>" name="businessExtrAA" id="enterPassengerDetailsForm.businessExtrAA" size="17" maxlength="10" pattern="[OB0-9]*" class="forceWidth-phone forceWidth6" />
Here is my Javascript code
var keepBusinessExtraMaxLength = function () {
var input = [];
jQuery("#enterPassengerDetailsForm\\.businessExtrAA").each(function(i) {
input[i]=this.defaultValue;
jQuery(this).data("idx",i);
});
jQuery("#enterPassengerDetailsForm\\.businessExtrAA").on("keyup", function (e) {
var field = jQuery(this);
var val=this.value;
var maxLength=isNaN(jQuery(field).val()) ? Number(jQuery(field).attr("maxlength")) : 6;
var thisIndex=jQuery(field).data("idx");
if (this.validity && this.validity.badInput || jQuery(field).is(":invalid") ) {
this.value = input[jQuery(thisIndex)];
return;
}
if (val.length > maxLength) {
val=val.slice(0, maxLength);
jQuery(field).val(val);
}
input[jQuery(thisIndex)]=val;
});
}
Your Regex seems to be matching only the characters , O, B and other numbers...
To make it match
6 digits or OB followed by 8 digits only
You can use this regex: ^(?:[0-9]{6}|OB[0-9]{8})$
Demonstration: http://www.regexpal.com/?fam=96586

How to restrict decimal value for two digits and restrict decimal more than one in numeric value

I have one amount field in that i want to restrict user after decimal they can not use more than two values:
After decimal there should be only two values that are option.
User can not type more than one decimal in the field.
I am using following regix for that its not working can any one help.
function validate(evt) {
if (evt.keyCode == 8) { return true; }// for backspace problem in mozilla
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
var regex = /[0-9 ]|\,\d{1,2}/;
if (!regex.test(key))
{
theEvent.returnValue = false;
if (theEvent.preventDefault) theEvent.preventDefault();
}
}
This can actually be accomplished using HTML only by setting the STEP and MAX of your numeric field such as
<form>
<input type="number" name="myNumber" required=true step=".01">
<button>send</button>
</form>
please let me know if this is what your looking for but this will mean that any value entered must be numeric(thus only 1 decimal point) it must be less than or equal to 1 (you can set to .99 if you dont want to include 1) and it must be an increment of .01(so it can only have 2 decimal places.
Just re-read your question you can remove the max(i thought i read no more than 1.0)
var previousValue;
function numberChanged(element){
if(validateMe(element)==false){
element.value=previousValue;
}else{
previousValue=element.value;
}
function validateMe(element){
wholeNumber=element.value.split(".")[0];
if(element.value.split(".").length==1){
if(wholeNumber<-1 || > 999999999){
return false;
}
}else if(element.value.split(".").length==2){
decimalValue=element.value.split(".")[1];
if(decimalValue>-1 && decimalValue<100){
if(wholeNumber<-1 || > 999999999){
return false;
}
}else{
return false;
}
}else{
return false;
}
}
<input type="text" id="myNumber" onChange="numberChanged(this)" />

adding text to a only numeric text field for usability?

OK so i have this task that im not sure how to achieve. I have a text field that is only allowing the users to enter numeric values....I am validating on keypress to make sure that only numeric numbers are allowed
That works well
My problem is that the client wants text after the numbers to say " Miles" so if the user enters 100 they see "100 Miles"
I guess for usability. Does anyone know a good technique or jquery plugin to do this
In addition to a javascript solution, you may also want to look into the HTML 5 pattern attribute for <input>. For example, in modern browsers you could do something like:
<input name="miles" pattern="^\d+\s?[Mm]iles$" required>
Which requires no javascript at all :) Here's the relevant spec.
How about this:
$('input').keypress(function(e) {
if (e.which < 48 || e.which > 57) {
// not a number
return false;
}
// gets current entered numer
var number = this.value.split(' ')[0];
// adds new number
number = '' + number + String.fromCharCode(e.which);
this.value = number + ' miles';
return false;
})
It would be easier and I think clearer to do this in some sort of tag just outside of the textbox. Have a span directly below or something then update it on your keypress.
$('#textBox').keydown(function(){
// Validation code
$('#someSpan').html($(this).val() + " Miles");
});
How about this http://jsfiddle.net/TmxSN/1/
$(function(){
var timerOutId;
$('#inp').keypress(function(e) {
var key = e.which;
clearTimeout(timerOutId);
try{
if(this.value){
this.value = $.trim(this.value.match(/\d+/g)[0]);
}
}catch(e){}
if ((key < 48 || key > 57) && !(key == 8 || key == 9 || key == 13 || key == 37 || key == 39 || key == 46) ){
return false;
}
}).keyup(function(e) {
var textBox = this;
if(this.value){
timerOutId = setTimeout(function(){
textBox.value = $.trim(textBox.value.match(/\d+/g)[0]) + " Miles";
}, 2000);
}
})
});
My problem is that the client wants text after the numbers to say "
Miles" so if the user enters 100 they see "100 Miles"
Then you can handle it in the onfocus and onblur event of your input type="text" like this.
Try this
<input type="text" min="0" max="1000" step="1" id="distance" placeholder="Enter the value in miles"/>
And Script
$(document).ready(function() {
//$("#distance").keypress(PassNumbersOnly);
$("#distance").focus(OnFocus);
$("#distance").blur(OnBlur);
});
function OnFocus() {
var $this = $(this);
if ($this.val().indexOf("Miles") != -1) {
$this.val($this.val().split(" ")[0]);
}
}
function OnBlur() {
var $this = $(this);
if ($.trim($this.val()) != "") {
$this.val($this.val() + " Miles");
}
}
Demo here: http://jsfiddle.net/naveen/EQEMr/
Tell your client that anyone with enough intelligence to use the web can understand:
<label for="distance">Distance in miles:
<input type="text" name="distance" id="distance"></label>
and that doing anything else is:
confusing for users
problematic as javascript may or may not be enabled/available
of zero practical use for the business as the value must be validated on the server anyway
the value requires additional processing at the server to remove the appended characters

Categories