-1

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 ?

tereško
  • 57,247
  • 24
  • 95
  • 149
Neo
  • 14,469
  • 52
  • 188
  • 369

4 Answers4

2
function returnDoubleDigits(str) {
  return str.length === 1 ? '0' + str : str;
}

e.g.

var HourPerWeek = returnDoubleDigits($("#Hour").val());

Fiddle

Andy
  • 53,323
  • 11
  • 64
  • 89
0

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();
}
Morne
  • 1,583
  • 1
  • 17
  • 32
0

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'
Community
  • 1
  • 1
Jan
  • 1,356
  • 10
  • 12
-2

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
}
Jay
  • 975
  • 4
  • 22
  • 38