Adding a 0 before digit in an input - javascript

I need help when you enter a single digit month in a date of birth that will automatically add a 0 digit in a single digit in an input.Here's my code:
$('#dob_dd').blur(function(){
var addzero = $('#dob_dd').val().length;
if (addzero.length != 2) {
addzero = '0' + addzero;
} else {
return addzero;
}
});

If you want to update the displayed value. it's as simple as
$('#dob_dd').blur(function(){
var $this = $(this);
$this.value(('0' + $this.value()).substr(-2));
});
This will function correctly if the selector selects multiple targets as well

You already specify that you want to check the length of $('#dob_dd'). So maybe it should be :
if (addzero != 2)
Then of course you need to update the value using for instance $('#dob_dd').val("new value")

Related

How to auto add slash(/) in expiry date field input javascript

I wanna auto add slash in credit card expiry date field input. I wanna add slash after type 2 character and remove slash after delete third digit. Example, 23/ (auto add slash after type number 3) 23/4 (auto remove slash after delete number 4)
addSlashes(elementID) {
let ele = document.getElementById(elementID)
const value = ele.value
let finalVal = null
if (value.length === 2) {
finalVal = `${value}/`
}
document.getElementById(elementID).value = finalVal
},
As soon as the / is added after 2 characters, the total length becomes 3. So, it is not very clear how the operation should happen.
However, if this is for some automatic changes to happen when progressive typing takes place, here is the code to add a / automatically when the user has typed 2 characters and remove it when the next character is added after the /
Edit
OP needs to delete the / when the 3rd digit is removed.
function modifyInput(ele) {
if (ele.value.length === 2)
ele.value = ele.value + '/'
else
if (ele.value.length === 3 && ele.value.charAt(2) === '/')
ele.value = ele.value.replace('/', '');
}
<input type="text" onkeyup="modifyInput(this)">

Is there a better way to update html text box string format to HH:MM:SS using jQuery

Alright, after digging through several sites...I am sure there is a better way to get the result I am looking for. Users are entering data in a text box on an HTML form and I want the format to change from 152000 (HHMMSS) to 15:20:00 (HH:MM:SS)
I was able to Frankenstein the jQuery below and it does work but I'm sure there is a better way to achieve the same result. I know I could handle the data after submission but would prefer to use jQuery to update it as they type. From what I read, I could use some type of time format but everything was focused on time as a date and I just need this to be a string that adds a colon after every two digits and limits the length to 8. Any thoughts?
$('#amount').keypress(function() {
// limits the charachters allowed
var regex = new RegExp("^[0-9:]");
var key = String.fromCharCode(event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
//adds a colon after 2 digits typed
if(this.value.length == 2){
this.value = this.value+':';
}
//adds a colon after 5 character
if(this.value.length == 5){
this.value = this.value+':';
}
//limit to 8 total characters
if(this.value.length > 7) {
return false;
}
});
$('#amount').keypress(function() {
let $input = $(this);
let value = $input.val();
let update = value.replace(/(\d{2})(\d{2})(\d{2})/, '$1:$2:$3');
// 120000 --> 12:00:00
$input.val(update)
})

how to append double digit if user passed single digit value using jquery

I'm working on jquery.
i want to check the validation on todate and from date.
want to convert my string into double digit (need to add 0 if user enter single digit value)
how can i give double digit as user enter single digit value into textbox?
expected output is
var HourPerWeek = $("#Hour").val();
-- if user enter value 2 i need to convert it into 02
var MinPerWeek = $("#Min").val();
-- if user enter value 1 i need to convert it into 01
Instead of length of string ?
function returnDoubleDigits(str) {
return str.length === 1 ? '0' + str : str;
}
e.g.
var HourPerWeek = returnDoubleDigits($("#Hour").val());
Fiddle
Would this work,just check the string length and then add a zero if it is shorter than 2
var HourPerWeek;
if ($("#Hour").val().length < 2){
HourPerWeek = "0"+ $("#Hour").val();
}
else{
HourPerWeek = $("#Hour").val();
}
You will have to add the 0 to the beginning of the string manually like in this example:
String.prototype.paddingLeft = function (paddingValue) {
return String(paddingValue + this).slice(-paddingValue.length);
};
var HourPerWeek = $("#Hour").val().paddingLeft('00');
Explanation: You can call paddingLeft on any string. It will add the chars, that you pass as an argument to the left of the string and return a string with exactly the length of the given argument. More examples:
''.paddingLeft('00') // returns '00'
'1'.paddingLeft('00') // returns '01'
'11'.paddingLeft('00') // returns '11'
'111'.paddingLeft('00') // returns '11'
'1'.paddingLeft(' ') // returns ' 1'
Have this as a function which checks for length of passed parameter.
function returnTwoDigit(var Data){
if (Data.length != 2) {
if (Data.length == 1) {
Data= "0" + Data;
}
return Data
}

Allow only 2 decimal points entry to a textbox using javascript or jquery?

I called a class called test for my textbox. When I entered the first value for e.g. the first value as 4., then suddenly the output coming as 4.00. I just want to restrict entry only for two decimal places.
$(".test").keyup(function (event) {
debugger;
this.value = parseFloat(this.value).toFixed(2);
});
This small change to your code may suffice:
this.value = this.value.replace (/(\.\d\d)\d+|([\d.]*)[^\d.]/, '$1$2');
Essentially replace the decimal point followed by any number of digits by a decimal point and the first two digits only. Or if a non digit is entered removes it.
What about something like this:
$(".test").keyup(function (event) {
if ((pointPos = this.value.indexOf('.')) >= 0)
$(this).attr("maxLength", pointPos+3);
else
$(this).removeAttr("maxLength");
});
Here is a working fiddle.
you can use the maxLength attribute for that, try
$(".test").keyup(function (event) {
var last = $(this).val()[$(this).val().length - 1];
if (last == '.') {
$(".test").attr("maxlength", $(this).val().length+2);
}
});
You shouldn't worry about what the user has in the input until they submit the form. You really don't care what's in there before then. However, if you want to warn about invalid input, you can put a message on the screen if you detect non–conforming input, e.g.
<script>
function validate(element) {
var re = /^\s*\d*\.?\d{0,2}\s*$/;
var errMsg = "Number must have a maximum of 2 decimal places";
var errNode = document.getElementById(element.name + '-error')
if (errNode) {
errNode.innerHTML = re.test(element.value)? '' : errMsg;
}
}
</script>
You should probably also put a listener on the change handler too to account for values that get there by other means.
$(document).on("keyup", ".ctc", function ()
{
if (!this.value.match(/^\s*\d*\.?\d{0,2}\s*$/) && this.value != "") {
this.value = "";
this.focus();
alert("Please Enter only alphabets in text");
}
});

jQuery Form, check first four numbers of variable

What I'm trying to achieve is a code checker. Only the first 4 numbers are important, the other numbers can be any number. The form will be used for users to put in productcodes.
The problem is that if the variable changes to say, 5 numbers the variable is false.
See below example:
http://jsfiddle.net/MZfxs/3/
If the user puts in the numbers 3541 the box changes color, but if the user put in the remaining numbers the value is set to false.
Additionally I'm trying to make the box only change color when 13 numbers are inserted AND the first 4 numbers are matching, in that order.
Solved!
Working Example:
http://jsfiddle.net/MZfxs/8/
If I understood correctly, you need a field value validation and the requirement is the value should start from 4 numbers like 7514 or 9268. Here you can use a regular expression to validate input value like:
// Will work for " 123433 " or "12345634 ", etc.
var value = $(this).val(),
re = /^\s*(\d{4})(\d+)\s*$/, // better to initialize only once somewhere in parent scope
matches = re.exec(value),
expectedCode = 3541,
expectedLength = 13;
if(!!matches) {
var code = matches[1]; // first group is exactly first 4 digits
// in matches[2] you'll find the rest numbers.
if(value.length == expectedLength && code == expectedCode) {
// Change the color...
}
}
Also if your requirement is strict to length of 13 than you can modify the regular epression to
var re = /^(\d{4})(\d{9})$/;
and retrieve first 4 numbers in first group and rest 9 in second group:
var matches = re.exec(value);
if(!!matches) {
var first4Digits = matches[1],
rest9Digits = matches[2];
// ...
// Also in this way you'll not need to check value.length to be 13.
}
You can break the string each time on key event fires. You can do this by calling js substring() method and take the first four characters and check it.
Try to use this:
<script>
$("input").keyup(function () {
var value = $(this).val();
$("p").text(value);
var value2 = $(this).val().substr(0,4);
if(value2 == 3541){
$(".square").css("background-color","#D6D6FF");
}else{
$(".square").css("background-color","yellow");
}
})
</script>

Categories