Reputation: 83697
This just seems absurd to me. Should I use array instead or is there some other better solution?
$('.hoursRange').change(function() {
if ('0' == $(this).val())
{
$(this).val('00');
return false;
}
if ('1' == $(this).val())
{
$(this).val('01');
return false;
}
if ('2' == $(this).val())
{
$(this).val('02');
return false;
}
if ('3' == $(this).val())
{
$(this).val('03');
return false;
}
if ('4' == $(this).val())
{
$(this).val('04');
return false;
}
if ('5' == $(this).val())
{
$(this).val('05');
return false;
}
if ('6' == $(this).val())
{
$(this).val('06');
return false;
}
if ('7' == $(this).val())
{
$(this).val('07');
return false;
}
});
Upvotes: 0
Views: 129
Reputation: 2956
I am not an expert on jQuery but it is awkward.
I would check boundary condition (0<=$(this).val()<=7)
and if not met return false
. Otherwise
var v = $(this).val();
v='0'+v;
$(this).val(v);
Upvotes: 0
Reputation: 519
$('.hoursRange').change(function() {
$(this).val( $(this).val().replace(/(\b\d\b)/,'0$1') );
}
I don't see you needing any conditional statements or additional expensive jQuery calls in here.
Upvotes: 0
Reputation: 342635
if($(this).val().length == 1) {
$(this).val('0' + $(this).val());
}
Or just pad all of the single digits with zeros on page load, rather than onchange:
$('.hoursRange option').filter(function() {
return $(this).val().length == 1;
}).each(function() {
$(this).val('0' + $(this).val());
});
Demo: http://jsfiddle.net/WKdWq/
Upvotes: 5
Reputation: 132197
Just use a regex:
$(this).val($(this).val().replace(/^[0-7]$/, "0$&"));
Upvotes: 5
Reputation: 50858
A function for zero-padding is available from this answer. Using that, you can simply do:
$('.hoursRange').change(function() {
$(this).val( zerofill($(this).val(), 2) );
}
Upvotes: 1
Reputation: 177786
$('.hoursRange').change(function() {
if (parseInt($(this).val(),10)<10) $(this).val("0"+parseInt($(this).val(),10));
}
Upvotes: 1
Reputation: 19821
var value = $(this).val();
if ($(this).val().length < 2) {
$(this).val('0' + value);
}
Upvotes: 1