-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
  • 58,060
  • 25
  • 98
  • 150
Neo
  • 15,491
  • 59
  • 215
  • 405

4 Answers4

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

e.g.

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

Fiddle

Andy
  • 61,948
  • 13
  • 68
  • 95
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,623
  • 2
  • 18
  • 33
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,394
  • 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
  • 1,037
  • 5
  • 23
  • 41