jQuery format date on input - javascript

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()+'/');
}
}

Related

Input Field Only Accepting Numeric Value Using Directive In Vue.js

I am new to Vue.js. I want an input field which accepts only numeric numbers and if the user enters any other value it will be replace with the empty string. Therefore, I want to add a custom directive to this field viz 'numericOnly'.
Code for custom directive :
Vue.directive('numericOnly', {
bind (el, binding, vnode) {
regex = /^[0-9]*$/
if(!regex.test(el.value)){
el.value = el.value.slice(0, -1)
}
}
})
Here is my template :
<input v-numericOnly name="mobileNumber" placeholder="Mobile Number" >
But it runs only the one time when the input field is bound to the DOM.
Please help me figure out this problem. Thank you in advance.
Your directive should listen keyup of the input element to achieve what you need:
Vue.directive('numericOnly', {
bind(el) {
el.addEventListener('keyup', () => {
let regex = /^[0-9]*$/
if (!regex.test(el.value)) {
el.value = el.value.slice(0, -1)
}
})
}
})
import Vue from 'vue'
Vue.directive('numericOnly', {
bind(el, binding, vnode) {
el.addEventListener('keydown', (e) => {
if ([46, 8, 9, 27, 13, 110, 190].indexOf(e.keyCode) !== -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()
}
})
}
})

Empty value is resulting in a NaN result

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.

JQuery : Keypress not working on first press

This is my code
$(currentClass).keypress(function (e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}
});
The only problem with this is that, every time I hit a key for the first time regardless a letter or a number, it shows up in my content editable span tag. However, the second time I hit a letter key the code works, it only accepts number. I have no idea what is wrong with this code in the first pressing of keys.
Use JQuery's .on() method.
$(currentClass).on("keypress",function (e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}
});
This is what I used
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;
}
// Ensure that it is a number and stop the keypress
if (($event.shiftKey || ($event.keyCode < 48 || $event.keyCode > 57)) && ($event.keyCode < 96 || $event.keyCode > 105)) {
$event.preventDefault();
}
I was able to solve the problem with this. If their suggestion is not working try this.
Bind Properly your events
$(document).ready(function(){
$(body).on("keypress","currentClass",function (e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}
});
});
$(currentClass).on('keypress', function (e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
e.preventDefault();
alert("pressed");
return false;
}
});
event - on
This might helps you :)

Restriciting enterting of alphabets in jquery mobile

I am using a text box with type number. For xperia mobile's if i am using the same text box,it is showing a keyboard with all the value.So i am able to type any value. I want to restrict the user from entering any value.User have to enter only number.I tried the following code.
*
document.getElementById('loginPin').addEventListener('keyup', function(e){
var keyCode = ('which' in e) ? e.which : e.keyCode;
var isNumeric = (keyCode < 48 KeyboardEvent.DOM_VK_0 && keyCode > 57 KeyboardEvent.DOM_VK_9 ) ||
(keyCode < 96 KeyboardEvent.DOM_VK_NUMPAD0 && keyCode > 105 KeyboardEvent.DOM_VK_NUMPAD9 );
var modifiers = (event.altKey || event.ctrlKey || event.shiftKey);
return !isNumeric || modifiers;
var V = $(this).val();
alert("hai"+V);
if (isNaN(V)) {
$(this).val(V.replace(/[^0-9]/g,''));
}
}, false);
*
It is working if the alert is there, else it is not working. So any suggestion to solve this.
function numericInput(inputId){
$('#' + inputId).keyup(function (e) {
var regex = new RegExp("^[0-9]+$");
if (!regex.test($(this).val())) {
$(this).val($(this).val().slice(0, -1));
e.preventDefault();
return false;
}
});
}

Restrict to input minus symbol

I need to restrict user to input minus symbol. How to do it useing following jQuery I have got?
$("#Age").keydown(function (e) {
// Allow: backspace, delete, tab, escape, enter
if ($(this).val().length <= 2 || $.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
(e.keyCode >= 35 && e.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
else {
event.preventDefault();
}
// Ensure that it is a number and stop the keypress
if ($(this).val().length <= 2 || (e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
else {
event.preventDefault();
}
});
}); // end of $
ASCII key codes
Minus symbol ASCII value is 45
$("#Age").keydown(function (e) {
if (e.keyCode != 45) { //it does't allow user to enter minus(-) symbol
..
}
else {
event.preventDefault();
}
}); // end of $

Categories

Resources