Empty value is resulting in a NaN result - javascript

My form displays NaN when the input fields are empty. Can you help me to handle this issue? Here’s my code:
function dailyRate () {
var monthlyRate = parseInt(document.getElementById("txt1").value);
var months = 12;
var workingDays = parseInt(document.getElementById("txt2").value);
var totalDailyRate = (monthlyRate * months) / workingDays;
document.getElementById("totalRate").innerHTML = Math.round(totalDailyRate);
}
$(document).ready(function() {
$("#mainForm").submit(function(e){
e.preventDefault();
});
$("#txt2, #txt1").keydown(function (e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: Ctrl+C
(e.keyCode == 67 && e.ctrlKey === true) ||
// Allow: Ctrl+X
(e.keyCode == 88 && e.ctrlKey === true) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form name="mainForm" id="mainForm" action="" onsubmit="return dailyRate()" method="post">
<input type="text" id="txt1" name="text1" placeholder="monthlyrate">
<input type="text" id="txt2" name="text2" placeholder="workingDays">
<p id="alerttext"></p>
<button>Submit</button>
<p id="totalRate"></p>
</form>

The function parseInt() returns NaN if the content is not a number, in your case, if the control is empty, the return of getElementById will return an empty string. So probably you should perform some validation before using it, like:
var monthlyRate = parseInt(document.getElementById("txt1").value);
var months = 12;
var workingDays = parseInt(document.getElementById("txt2").value);
if (isNaN(monthlyRate) || isNaN(workingDays)) {
document.getElementById("totalRate").innerHTML = 'No value';
return;
}
In the example above, if any of the values are invalid, the totalRate will display 'No value'.

Check if the value is NaN or not. If it is NaN, you can set the value to 0 or show an error message:
var textField1 = document.getElementById("txt1");
var textField2 = document.getElementById("txt2");
var monthlyRate = parseInt(textField1.value);
var workingDays = parseInt(textField2.value);
if (isNaN(monthlyRate)) {
textField1.value = 0;
monthlyRate = 0;
}
if (isNaN(workingDays)) {
textField2.value = 0;
monthlyRate = 0;
}
OR:
if (isNaN(totalDailyRate)) {
document.getElementById("totalRate").innerHTML = "Please enter valid numbers";
} else {
document.getElementById("totalRate").innerHTML = Math.round(totalDailyRate);
}
Suggestion: If you use <input type="number">, modern browsers display controls for increasing and decreasing the number in the input field.

Related

Allow 2 digit number after the decimal

Hi i am trying to restrict user to input 2 digit number after the decimal.The below functionality is working but i am not able to modify the last two digit.suppose I have entered number 3456.78 and i want to modify 3456.68 it is not allowing.
$('.PMT_AMT').keypress(function(event) {
var $this = $(this);
if ((event.which != 46 || $this.val().indexOf('.') != -1) &&
((event.which < 48 || event.which > 57) &&
(event.which != 0 && event.which != 8))) {
event.preventDefault();
}
var text = $(this).val();
if ((event.which == 46) && (text.indexOf('.') == -1)) {
setTimeout(function() {
if ($this.val().substring($this.val().indexOf('.')).length > 3) {
$this.val($this.val().substring(0, $this.val().indexOf('.') + 3));
}
}, 1);
}
if ((text.indexOf('.') != -1) &&
(text.substring(text.indexOf('.')).length > 2) &&
(event.which != 0 && event.which != 8) &&
($(this)[0].selectionStart >= text.length - 2)) {
event.preventDefault();
}
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<input type="text" class="PMT_AMT">
Here's one possibility that uses a regular expression. Save the old input value on keypress, and if the new value on keyup does not validate, reset to that old value.
You need to validate on keypress as well, because otherwise, if the user types very fast, an invalid value can be saved:
const re = /^\d+(\.\d{0,2})?$/;
let oldVal;
$('.PMT_AMT').keypress(function(event) {
const { value } = this;
if (re.test(value)) oldVal = value;
});
$('.PMT_AMT').keyup(function(event) {
const newVal = this.value;
if (!re.test(newVal)) this.value = oldVal;
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<input type="text" class="PMT_AMT">
This solution creates a prediction and tests the regular expression against that instead.
$('.PMT_AMT').keypress(function(event) {
if(!/^\d*(\.\d{0,2})?$/.test(
this.value.slice(0, this.selectionStart)
+ String.fromCharCode(event.which)
+ this.value.slice(this.selectionEnd)
)) event.preventDefault();
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<input type="text" class="PMT_AMT">
Why use jQuery and not just browser functionality?
<input type="number" step="0.01">
On submit the browser will check if the submitted value of the input field has maximum two decimals.

jQuery format date on input

I'm trying to format a date as the user enters into the input field by assigning a class to it which is inside a function. I know its firing but something is quite right its throwing [object] in the input field. My end goal is as the user types it will throw a / after the first two characters and then another / after the next two: 01/01/2017
CODE:
$(document).off('keydown', '.dateField');
$(document).on('keydown', '.dateField', function(e){
var start = this.selectionStart,
end = this.selectionEnd;
if($(this).val().replace(/[^\d]/g,"").length<$(this).val().length)
end = end-1;
$(this).val($(this).toString().substr(0,2)+"/"+$(this).toString().substr(2));
this.setSelectionRange(start, end);
}
UPDATED CODE:
$(document).on('keydown', '.dateField', function(e){
$(this).attr('maxlength', '10');
var key=String.fromCharCode(e.keyCode);
if(!(key>=0&&key<=9)){
$(this).val($(this).val().substr(0,$(this).val().length-1));
}
var value=$(this).val();
if(value.length==2||value.length==5){
$(this).val($(this).val()+'/');
}
This is not preventing letters and symbols how do i add regex to prevent this problem. (super noob at egex)
Final Code:
$(document).off('keydown', '.dateField');
$(document).on('keydown', '.dateField', function(e){
$(this).attr('maxlength', '10');
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A, Command+A
(e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
// Allow: home, end, left, right, down, up
(e.keyCode >= 35 && e.keyCode <= 40)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
var value=$(this).val();
if(value.length==2||value.length==5){
$(this).val($(this).val()+'/');
}
}

Input validation for Number (user cant input less than 163)

I want to restrict user from giving value less than 163.
I already tried
<input type="text" class="inputnw" name="semesterCode" min="163" value="163" />
I have used text as i dont want to show increment/decrement at the right side of input box.
I want validation for anything below 163 and User can only type numeric number.
You can use this script. Whenever you enter a number less than 163 it will give an alert saying "Number must be less than 163"
function myFunction(){
var x = document.getElementById("number").value;
if ( x.length > 2 && x < 163 ) {
document.getElementById("error").innerHTML = "Please enter a number less than 163"
return false
}else{
return true
}
}
<input type="text" id="number" class="inputnw" name="semesterCode" onkeyup="myFunction()"/>
<span id="error" style="color:red"></span>
Use type=number for the input field! it is really feasible and effective and use the following style to disable the arrows for the input box
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
input[type="number"] {
-moz-appearance: textfield;
}
Sample Plunkr: https://plnkr.co/edit/LaApGngTkJL14mmTmi78?p=preview
Use below Jquery code (Remember i assumed you are using Jquery), Just apply this class "inputnw" for fields you want do this kind of validation.
$(document).ready(function () {
$(document).on('keypress keyup blur', '.inputnw', function (event) {
$(this).val($(this).val().replace(/[^0-9\.]/g, ''));
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(event.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A
(event.keyCode == 65 && event.ctrlKey === true) ||
// Allow: home, end, left, right
(event.keyCode >= 35 && event.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
if ($(this).val().length >= 3) {
if ($(this).val() < 163) {
$(this).val('');
alert('Please enter value greater than 163');
$(this).focus();
}
}
});
$('.inputnw').blur(function () {
if ($(this).val().length < 3) {
if ($(this).val() < 163) {
$(this).val('');
alert('Please enter value greater than 163');
$(this).focus();
}
}
});
});
You could change the type to number and do something like this using the validity object of the input object
<input type="number" class="inputnw" name="semesterCode" min="163" onblur="if(this.validity.rangeUnderflow)this.setCustomValidity('I expect 163');" />
You can add a listener to check the value based on some event. Let the user fix the value themselves and make the message user friendly:
function checkValue(){
var errorEl = document.getElementById(this.id + 'Error');
var message = 'Value must be ' + this.dataset.min + ' or greater';
if (errorEl) {
errorEl.textContent = +this.value >= +this.dataset.min? '' : message;
}
}
window.onload = function() {
var el = document.getElementById('semesterCode');
el.addEventListener('input', checkValue, false);
}
.errorMessage {
color: red;
font-family: sans-serif;
font-size: 80%;
}
<input name="semesterCode" id="semesterCode" data-min="163" value="163"><br>
<span id="semesterCodeError" class="errorMessage">

When pasteing value into input area, can't capture value

I have a button and an input area. When the input's length is filled (14) - then the button's class will be active. That currently works, however, when the user pastes a value into the input area, the length is zero until the user enters something else. My goal is to display the active class on the button when the paste is done if the length of the value is 14.
JS
$('#number', '#form')
.keydown(function (e) {
var key = e.charCode || e.keyCode || 0;
$phone = $(this);
$len = $phone.val().length;
console.log($len);
// Auto-format
if (key !== 8 && key !== 9) {
if ($phone.val().length === 13){
$('#form div a:eq(0)').removeClass('inactive');
}
if (($phone.val().length === 14) && (key == 13)){
e.preventDefault();
$('#form div a:eq(0)').trigger('click');
}
if ($phone.val().length < 13){
$('#form div a:eq(0)').addClass('inactive');
}
}
if (key == 8){
$('#form div a:eq(0)').addClass('inactive');
}
// Allow numeric, tab, backspace, delete, and arrow keys only
return (
key == 8 ||
key == 9 ||
key == 46 ||
key == 86 || //copy+paste
key == 67 ||
key == 17 ||
key == 91 || // end
(key >= 37 && key <= 40)||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105)
);
});
document.getElementById('number').addEventListener('input', function (e) {
var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
e.target.value = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');
});
HTML
<form id="form">
<input id="number" type="text" maxlength="14" placeholder='(100) 100-1000'>
<div>
<a class='bt inactive'>Enter</a>
</div>
</form>
You should use the input event. This event is triggered when eve the input changes. keyup and keydown will fire even if the input hasn't changed. Pressing CTRL will trigger keydown even if nothing has changed. input will only be triggered if it has changed, ie: CTRL + V (paste)
$('#number', '#form')
.on('input', function (e) {
var key = e.charCode || e.keyCode || 0;
$phone = $(this);
$len = $phone.val().length;
console.log($len);
// Auto-format
if (key !== 8 && key !== 9) {
if ($phone.val().length === 13){
$('#form div a:eq(0)').removeClass('inactive');
}
if (($phone.val().length === 14) && (key == 13)){
e.preventDefault();
$('#form div a:eq(0)').trigger('click');
}
if ($phone.val().length < 13){
$('#form div a:eq(0)').addClass('inactive');
}
}
if (key == 8){
$('#form div a:eq(0)').addClass('inactive');
}
// Allow numeric, tab, backspace, delete, and arrow keys only
return (
key == 8 ||
key == 9 ||
key == 46 ||
key == 86 || //copy+paste
key == 67 ||
key == 17 ||
key == 91 || // end
(key >= 37 && key <= 40)||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105)
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form">
<input id="number" type="text" maxlength="14" placeholder='(100) 100-1000'>
<div>
<a class='bt inactive'>Enter</a>
</div>
</form>
Also use another event input so it triggers your function on keydown and on input as well. Check out this working example using your code
$('#number', '#form').on('keydown input',function(){});
$('#number', '#form')
.on('keydown input', function (e) {
var key = e.charCode || e.keyCode || 0;
$phone = $(this);
$len = $phone.val().length;
console.log($len);
// Auto-format
if (key !== 8 && key !== 9) {
if ($phone.val().length === 13){
$('#form div a:eq(0)').removeClass('inactive');
}
if (($phone.val().length === 14) && (key == 13)){
e.preventDefault();
$('#form div a:eq(0)').trigger('click');
}
if ($phone.val().length < 13){
$('#form div a:eq(0)').addClass('inactive');
}
}
if (key == 8){
$('#form div a:eq(0)').addClass('inactive');
}
// Allow numeric, tab, backspace, delete, and arrow keys only
return (
key == 8 ||
key == 9 ||
key == 46 ||
key == 86 || //copy+paste
key == 67 ||
key == 17 ||
key == 91 || // end
(key >= 37 && key <= 40)||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105)
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form">
<input id="number" type="text" maxlength="14" placeholder='(100) 100-1000'><br /><br />
<div>
<a class='bt inactive'>Enter</a>
</div>
</form>

jquery keydown for only digits

i have an input box that is for payments, and i want to only allow number like x.xx, of course xxxx.x will work or xxxxx
i have the setup pretty much working minus some weird behavior. if the numbers 1 and 2 after the decimal can be 2 digits long (works) but if i press 3-9 then it only allows one of that digit. also 0's to the right of the decimal are being allowed infinitely.
heres what im working with. also i want to only allow the enter button and when its pressed then run a function
$('#money-button-input-box').keydown(function(event) {
var str = $(this).val()
if(str.length >= 1){
var rightHalf = str.split('.')[1];
if(rightHalf >= 3 && event.keyCode != 8 ){
event.preventDefault();
}
}
if( (event.keyCode == 190 || event.keyCode == 110) && str.replace(/[^.]/g, "").length >= 1 ){
event.preventDefault();
}
allowOnlyNumbers(event);
if (event.keyCode == 13) {
if($(this).val() == '')return;
enterPayment($(this));
}
});
and the function
function allowOnlyNumbers(events){
// Allow: backspace, delete, tab, escape, and enter
if ( events.keyCode == 46 || events.keyCode == 8 || events.keyCode == 9 || events.keyCode == 27 || events.keyCode == 13 ||
// allow decimals
events.keyCode == 190 || events.keyCode == 110 ||
// Allow: Ctrl+A
(events.keyCode == 65 && events.ctrlKey === true) ||
// Allow: home, end, left, right
(events.keyCode >= 35 && events.keyCode <= 39)) {
// let it happen, don't do anything
return;
} else {
// Ensure that it is a number and stop the keypress
if (events.shiftKey || (events.keyCode < 48 || events.keyCode > 57) && (events.keyCode < 96 || events.keyCode > 105 )) {
events.preventDefault();
}
}
}
http://jsfiddle.net/Qxtnd/
The problem of decimals is because you are using
rightHalf >= 3
which evaluates the actual number & not it's length, because javascript type-casts it to a number for the comparison. What you want instead is the number of digits, try
rightHalf.toString().length >= 2
Fiddle here http://jsfiddle.net/Qxtnd/1/
Edit
As long as rightHalf is a string you can do:
rightHalf.length >= 2
if rightHalf was a number you would get an exception doing that.
function isNumberKeyUp(event, obj, beforeLength, afterLength) {
var text = document.getElementById(obj).value;
var splitText = text.split('.');
if (splitText.length > 1 && splitText[1].length > afterLength) {
document.getElementById(obj).value = splitText[0] + "." + splitText[1].substring(0,2);
return false;
}
return true;
}
function isNumberKey(event, obj,beforeLength,afterLength) {
var keyCode1 = event.keyCode;
var keyCode = 0;
if (keyCode1 == 0)
keyCode = event.which;
else {
keyCode = keyCode1;
}
if ((keyCode >= 48 && keyCode <= 57) || keyCode == 46 || keyCode == 13 || keyCode == 27 || keyCode == 127 ) {
var text = document.getElementById(obj).value;
if (keyCode == 46 && keyCode1 == 0) {
if (text.toString().indexOf(".") != -1) {
return false;
}
}
if (keyCode == 46) {
if (text.toString().indexOf(".") != -1) {
return false;
}
}
var splitText = text.split('.');
if (splitText[0].length >= beforeLength) {
if (keyCode == 46 && text.toString().indexOf(".") == -1) {
return true;
} else if (text.toString().indexOf(".") != -1)
{
return true;
}
return false;
}
}
else {
return GetDefault(event);
}
return true;
}
function GetDefault(event) {
var keyCode = event.keyCode;
if (keyCode == 0)
keyCode = event.which;
if (keyCode == 8 || keyCode == 9 || keyCode == 35 || keyCode == 36 || keyCode == 37 || keyCode == 38 || keyCode == 39 || keyCode == 40 || keyCode == 46 || keyCode == 118) {
return true;
}
return false;
}
Below is the html to call this events
<input type="text" onkeyup="return isNumberKeyUp(event,'txtID',9,2);" onkeypress="return isNumberKey(event,'txtID',9,2);" required="required" id="txtID" maxlength="12" value="1.00" name="txtID">
Here's the FIDDLE
rightHalf.length >= 2
$('#money-button-input-box').keyup(function () {
$(this).val(FormatNumber($(this).val()));
});
function FormatNumber(val){
var split = val.split('.');
if (split.length>1) return OnlyNumbersAllowed(split[0])+'.'+OnlyNumbersAllowed(split[1]);
else return OnlyNumbersAllowed(split[0]);
}
function OnlyNumbersAllowed(val){
return val.replace(/\D/g, '');
}
http://jsfiddle.net/Qxtnd/7/
You could easly put this regex in any function, instead of writing what you have now.

Categories

Resources