i have input numeric field with format like 20,000.00
how to remove Nan if user not key in the first field?
document.getElementById("BasicSalary_x").onblur =function (){
this.value = parseFloat(this.value.replace(/,/g, ""))
.toFixed(2)
.toString()
.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
function isNumberKey(evt) {
var charCode = ((evt.which) ? evt.which : event.keyCode);
return !(charCode > 31 && (charCode != 46 && charCode != 44 && (charCode < 48 || charCode > 57)));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="tel" onkeypress="return isNumberKey(event)" id="BasicSalary_x" placeholder="Basic Salary (RM)" >
<input type="tel" value="0.00" onkeypress="return isNumberKey(event)" id="deduction" placeholder="Deduction (RM)" >
If you get NaN with parseFloat, then you can use ||0 to convert it to zero (or any default you prefer).
parseFloat("x,xx".replace(/,/g, "")) || 0
Alternatively, you can check if it's a number with isNaN
var val = this.value.replace(/,/g, "");
if (isNaN(val)) {
alert("Please only enter valid values.");
} else {
... parseFloat(val) ...
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN
Related
I'm trying to avoid input of any marks except numbers and letters with input string on my page.php:
<input type="text" id="input">
From this answer only allow English characters and numbers for text input <input type="text" id="input" class="clsAlphaNoOnly"> :
$(document).ready(function () {
$('.clsAlphaNoOnly').keypress(function (e) { // Accept only alpha numerics, no special characters
var regex = new RegExp("^[a-zA-Z0-9 ]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
e.preventDefault();
return false;
});
})
or this:
$(function(){
$("#input").keypress(function(event){
var ew = event.which;
if(ew == 32)
return true;
if(48 <= ew && ew <= 57)
return true;
if(65 <= ew && ew <= 90)
return true;
if(97 <= ew && ew <= 122)
return true;
return false;
});
});
in both cases string is clear, but I'm using two types of input with button click $("#btn").click(function() to process input and $(document).keypress(function(e) with hit on enter key on keyboard for same input. By some reason if I include this methods to avoid extra marks in string, pressing on enter key does not allows to input inserted value.
This way works fine:
<input type="text" id="input" onkeypress="return (event.charCode >= 65 && event.charCode <= 90) || (event.charCode >= 97 && event.charCode <= 122) || (event.charCode >= 48 && event.charCode <= 57)" />
but I want avoid extra code with html in page.php. I'm trying to figure out, what causes blocking of entering for inserted value with given methods
Would tell you may miss event parameter ?
Without jQuery works like this for me in 3 browsers:
function clsAlphaNoOnly (e) { // Accept only alpha numerics, no special characters
var regex = new RegExp("^[a-zA-Z0-9 ]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
e.preventDefault();
return false;
}
function clsAlphaNoOnly2 () { // Accept only alpha numerics, no special characters
return clsAlphaNoOnly (this.event); // window.event
}
<input type="text" id="input" onkeypress="clsAlphaNoOnly(event)" onpaste="return false;">
<input type="text" id="input" onkeypress="clsAlphaNoOnly2()" onpaste="return false;">
One way of validation is using pattern attribute on input element
MDN: https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation#Validating_against_a_regular_expression
In your case:
<input type="text" pattern="[a-zA-Z0-9]*">
If you really do not want to use the Regex method as the comments bellow advice you, then you can use this simple code :
document.querySelector("input#testInput").addEventListener("input", function(){
const allowedCharacters="0123456789azertyuiopqsdfghjklmwxcvbnAZERTYUIOPQSDFGHJKLMWXCVBNzáàâãéèêíïóôõöúçñÁÀÂÃÉÈÍÏÓÔÕÖÚÇÑ "; // You can add any other character in the same way
this.value = this.value.split('').filter(char => allowedCharacters.includes(char)).join('')
});
<input type="text" id="testInput">
Instead of javascript you could use a pattern along with required. pattern will allow you to specify a required pattern for the input, and required will make the input required. Both must evaluate to true in order for the form to submit.
<form>
<input type="text" id="input" pattern="[a-zA-Z0-9]+" required>
<input type="submit">
</form>
HTML Input Way :
1- Simple HTML5 Input
<input type="text" pattern="[a-zA-Z0-9]*">
2- Inline Function
<input type="text" id="input" onkeypress="return (event.charCode >= 65 && event.charCode <= 90) || (event.charCode >= 97 && event.charCode <= 122) || (event.charCode >= 48 && event.charCode <= 57)" />
Jquery Way :
$('#ID').on('keypress', function (e) { var code = ('charCode' in e) ? e.charCode : e.keyCode; if (!(code > 47 && code < 58) && !(code > 64 && code < 91) && !(code > 96 && code < 123)) {e.preventDefault();}});
Javascript Function :
function allowAlphaNumericSpace(e) {
var code = ('charCode' in e) ? e.charCode : e.keyCode;
if ( !(code > 47 && code < 58) && !(code > 64 && code < 91) && !(code > 96 && code < 123)) { e.preventDefault();}};
<input type="text" onkeypress="allowAlphaNumeric(event)" />
I'm making web application that requires users to enter number with one decimal place. I restrict users from entering other characters that numbers from using this javascript code
html
<input type="number" name='days' class="w3-input w3-padding-tiny" id="cntday" onkeypress="return isNumberKey(event)" placeholder="Enter days"/>
javascript
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode != 46 && charCode > 31 &&
(charCode < 48 || charCode > 57))
return false;
return true;
}
but this function only prevent users from entering characters other than numbers.
I need to prevent users from entering more than one decimal places as well as entered decimal should be .5
it's like this
if user enter 5.55 it should replace with 5.5 OR prevent user to input additional decimal
and if user enter 5.2 OR any decimal it should be replace with 5.5 in other words users should only able to enter number with decimal .5
how can I achieve this with my current onkeypress function ?
This is NOT a duplicate of the other question. Stop flagging this
You can do it by split the number into two parts:
Part 1 for natural number.
Part 2 for decimal number.
then you can replace any entered decimal number to .5
Something like this:
$('input').keyup(function() {
var value = this.value;
var pos = value.indexOf(".");
var result;
if (pos !== -1) {
var part1 = value.substr(0, pos);
var part2 = value.substr(pos);
result = part1 + part2.replace(part2,".5")
$('input').val(result);
}
});
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode != 46 && charCode > 31 &&
(charCode < 48 || charCode > 57))
return false;
return true;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" name='days' class="w3-input w3-padding-tiny" id="cntday" onkeypress="return isNumberKey(event)" placeholder="Enter days"/>
Use this
$('#cntday').keyup(function() {
if(this.value %1 != 0.5){
this.value = this.value - this.value%1 + 0.5;
}
});
The condition checks whether a decimal has been entered or not and as soon as a decimal is entered and a number is entered it changes it to .5
It fulfills both the requirements you mentioned.
Check it here https://jsfiddle.net/xn0koawx/
I want to remove first space from text field. i have created function which allow only characters.
Here is my html code :
<form:input path="deliveryBoyName" id="deliveryBoyName"
maxlength="100" class="form-control"
onkeypress="return onlyAlphabets(event,this);">
</form:input>
Here is my javascript function :
function onlyAlphabets(e, t) {
try {
if (window.event) {
var charCode = window.event.keyCode;
}
else if (e) {
var charCode = e.which;
}
else { return true; }
if (charCode == 0 || charCode == 8 || charCode == 17 || charCode == 20 || charCode == 32 || (charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123))
return true;
else
return false;
}
catch (err) {
alert(err.Description);
} }
Now if user first types space then it should remove. starts only from character.
For example :
If user types like " Hello World"
Then it should not allowed.
If user type like "Hello World" then its should allowed. please help me.
Thank you in advance.
JavaScript trim() function can remove white spaces from both the side.
Here is working fiddle -
var str = " Did you find solution Ashish? If yes then tick it.";
alert(str.trim());
I think you want to allow space only when it is not the first character.
This is what you want, i.e. your function removing all the unnecessary code:
function onlyAlphabets(e, t) {
var charCode = e ? e.which : window.event.keyCode;
return (charCode == 0 || charCode == 8 || charCode == 17 || charCode == 20 ||
(t.value.length && charCode == 32) ||
(charCode > 64 && charCode < 91) ||
(charCode > 96 && charCode < 123))
}
I want to enter a decimal point in a text box. I want to restrict the user by entering more than 2 digits after the decimal point. I have written the code for achieving that in the Keypress event.
function validateFloatKeyPress(el, evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
if (charCode == 46 && el.value.indexOf(".") !== -1) {
return false;
}
if (el.value.indexOf(".") !== -1)
{
var range = document.selection.createRange();
if (range.text != ""){
}
else
{
var number = el.value.split('.');
if (number.length == 2 && number[1].length > 1)
return false;
}
}
return true;
}
<asp:TextBox ID="txtTeamSizeCount" runat="server" onkeypress="return validateFloatKeyPress(this,event);" Width="100px" MaxLength="6"></asp:TextBox>
The code is working but the issue is: if I enter ".75" and then change it to "1.75", it is not possible. Only way to do it is delete it completely and then type "1.75". This issue occurs if there are already 2 digits after decimal in the textbox. The conditions that I impose are
a) After decimal is present, it must at least have 1 or 2 digits. For ex .75 or .7 or 10.75 or 333.55 or 333.2 is accepted. but not .753 or 12.3335
b) Before the decimal, it not a must for the user to enter a value. User must also be able to enter integer numbers also.
Can you tell me what could be the issue?
Thanks,
Jollyguy
You were almost there. Just check that there are no more than 2 characters after the decimal.
UPDATE 1 - check carat position to allow character insertion before the decimal.
UPDATE 2 - correct issue pointed out by ddlab's comment and only allow one dot.
function validateFloatKeyPress(el, evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
var number = el.value.split('.');
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
//just one dot (thanks ddlab)
if(number.length>1 && charCode == 46){
return false;
}
//get the carat position
var caratPos = getSelectionStart(el);
var dotPos = el.value.indexOf(".");
if( caratPos > dotPos && dotPos>-1 && (number[1].length > 1)){
return false;
}
return true;
}
//thanks: http://javascript.nwbox.com/cursor_position/
function getSelectionStart(o) {
if (o.createTextRange) {
var r = document.selection.createRange().duplicate()
r.moveEnd('character', o.value.length)
if (r.text == '') return o.value.length
return o.value.lastIndexOf(r.text)
} else return o.selectionStart
}
http://jsfiddle.net/S9G8C/1/
http://jsfiddle.net/S9G8C/203/
Consider leveraging HTML5's Constraint Validation API. It doesn't necessarily prevent typing invalid values, but the field is marked invalid and it halts submission of the <form> (by default). I added the <output> to illustrate why the browser considers e.g. "1.100" a valid value (it sees the numeric value as "1.1").
<input id="n" type="number" step=".01">
var
n = document.getElementById('n'),
o = document.getElementById('o'),
didInputN = function(e) {
o.value = n.valueAsNumber;
};
n.addEventListener('input', didInputN);
input:invalid {
color: white;
background-color: red;
}
<input id="n" type="number" step=".01">
<output id="o" for="n"></output>
Philosophically, you might consider this a more usable approach as it allows the user to paste an invalid entry and edit it directly in the field.
You can do it by another way with onchange event, to not restrict to user to type, rather just convert number after typing, to make uniform, like this,
function validateFloatKeyPress(el) {
var v = parseFloat(el.value);
el.value = (isNaN(v)) ? '' : v.toFixed(2);
}
<input id="aninput" type="text" onchange="validateFloatKeyPress(this);" />
45.846 should be 45.85 but in your code user needed to convert their-self and then they will type 45.85 directly
1.)No multiple decimals points.
2.)Two numbers after decimal point.
3.)Allow only Numbers and one decimal point(.).
This will help.jsFiddle
function decimalValidation(el, evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
var number = el.value.split('.');
if(charCode == 8) {
return true;
}
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
//just one dot
if(number.length>1 && charCode == 46){
return false;
}
//get the carat position
var caratPos = getSelectionStart(el);
var dotPos = el.value.indexOf(".");
if( caratPos > dotPos && dotPos>-1 && (number[1].length > 1)){
return false;
}
return true;
}
function getSelectionStart(o) {
return o.selectionStart
}
Hi #webvitaly The above code will work in IE too please check
And backspace after decimals not working in Mozilla i updated my answer.
this code is very complet, I change "." to ",":
can't "," in begin
can't write more ","
<script type="text/javascript">
function isNumberKey(evt, el) {
var charCode = (evt.which) ? evt.which : event.keyCode;
var number = el.value.split(',');
var caracter = el.value;
if (charCode != 44 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
if (charCode == 44 && caracter == "") {
return false;
}
if (charCode == 44 && caracter.indexOf(",") != -1) {
return false;
}
//get the carat position
var caratPos = getSelectionStart(el);
var dotPos = el.value.indexOf(",");
if (caratPos > dotPos && dotPos > -1 && (number[1].length > 1)) {
return false;
}
return true;
}
function getSelectionStart(o) {
if (o.createTextRange) {
var r = document.selection.createRange().duplicate()
r.moveEnd('character', o.value.length)
if (r.text == '') return o.value.length
return o.value.lastIndexOf(r.text)
} else return o.selectionStart
}
</script>
My problem was that I need it to show an error message in real time if the user is allowed only 2 decimals:
value = parseFloat(valueFromInput);
parseFloat(value.toFixed(2)) !== value // condition to check
The above code worked for me..toFixed converts the float to a string wit only 2 decimals and I have to convert back to float to check with the initial value if are the same.
P.S. And before this condition you should check if the value is NaN.
I have pain-time when making input that only allows float number with jquery library. my code can't prevent chacacter "." when it's becoming first input, can anyone guide me to solve this problem?
$('.filterme').keypress(function(eve) {
if ( ( eve.which != 46 || $(this).val().indexOf('.') != -1 )
&& ( eve.which < 48 || eve.which > 57 )
|| ( $(this).val().indexOf('.') == 0)
)
{
eve.preventDefault();
}
});
I use this - works for keyboard input or copy and paste
$('input.float').on('input', function() {
this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<input type="text" class="float" />
Explanation:
First regex replaces anything that's not a number or a decimal.
Second regex removes any instance of a second decimal.
I filter the first position input with the jQuery Caret plugin. Otherwise, once the dot is typed, it's already late to check where it was placed. I tried checking for the dot, then deleting the dot, but it does not look nice.
jQuery caret plugin:
http://examplet.buss.hk/js/jquery.caret.min.js
What I did:
http://jsfiddle.net/FCWrE/422/
Try it :)
$('.filterme').keypress(function(eve) {
if ((eve.which != 46 || $(this).val().indexOf('.') != -1) && (eve.which < 48 || eve.which > 57) || (eve.which == 46 && $(this).caret().start == 0)) {
eve.preventDefault();
}
// this part is when left part of number is deleted and leaves a . in the leftmost position. For example, 33.25, then 33 is deleted
$('.filterme').keyup(function(eve) {
if ($(this).val().indexOf('.') == 0) {
$(this).val($(this).val().substring(1));
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/caret/1.0.0/jquery.caret.min.js"></script>
<input type="text" class="filterme">
Regular expression would be my recommendation as well. If the value is being passed as a number and not a string you can use .toString to change it to a string and validate it with regular expression. For example:
var str = value.toString();
if(!str.match(/^-?[0-9]*[.][0-9]+$/)) {
alert("Value must be a float number");
return;
}
return value;
The above regex will match if the value passed is a floating point number. It accepts both negative and positive numbers. If you only want to accept positive numbers simply remove the '-?' from the expression. It will also fail if the value is simply zero '0' without any decimal point. If you want to accept zero simply add it as a condition to the 'if' statement.
You can use the above validation and an onchange event to prevent the user from entering a non-flot number.
Why not using Regular Expression
^[0-9]*[.][0-9]+$
Read code and test here..
You can use the following method, called on onkeypress event. Below is the HTML snippet followed by the JS method:
input type="text" onkeypress="return isNumberKey(event)" id="floor"
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode == 46){
var inputValue = $("#floor").val();
var count = (inputValue.match(/'.'/g) || []).length;
if(count<1){
if (inputValue.indexOf('.') < 1){
return true;
}
return false;
}else{
return false;
}
}
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)){
return false;
}
return true;
}
Note: The above code also ensures that you enter only single decimal in the input.
Here is my solution, works with negative numbers too (fiddle)
$("input").keypress(function (event) {
var inputCode = event.which;
var currentValue = $(this).val();
if (inputCode > 0 && (inputCode < 48 || inputCode > 57)) {
if (inputCode == 46) {
if (getCursorPosition(this) == 0 && currentValue.charAt(0) == '-') return false;
if (currentValue.match(/[.]/)) return false;
}
else if (inputCode == 45) {
if (currentValue.charAt(0) == '-') return false;
if (getCursorPosition(this) != 0) return false;
}
else if (inputCode == 8) return true;
else return false;
}
else if (inputCode > 0 && (inputCode >= 48 && inputCode <= 57)) {
if (currentValue.charAt(0) == '-' && getCursorPosition(this) == 0) return false;
}
});
function getCursorPosition(element) {
if (element.selectionStart) return element.selectionStart;
else if (document.selection)
{
element.focus();
var r = document.selection.createRange();
if (r == null) return 0;
var re = element.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
return rc.text.length;
}
return 0;
}
This works for me:
var str = document.getElementById('product_'+id_product).value;
if( !str.match(/^[0-9]*([.,][0-9]+)?$/) ) {
console.log("Value must be a number or float number");
}else{
console.log("The number is valid");
}
I hope this can help someone.
Regards!