Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Just wondering if anyone have suggestions on how to refactor this?

$(document).ready(function () {

        $("td,select,th").css("min-width", "150px");

        $("#cancel").button({
            disabled: true
        });
        $(".group-32 input").datepicker();
        $(".group-6 input").datepicker();

        $("#0LevelId").change(function () {
            var currentYear = (new Date).getFullYear();
            $("#0EffectiveDate").val("01/01/" + (currentYear + 1));
        });

        $("#1LevelId").change(function () {
            var currentYear = (new Date).getFullYear();
            $("#1EffectiveDate").val("01/01/" + (currentYear + 1));
        });

        $("#3LevelId").change(function () {
            var currentYear = (new Date).getFullYear();
            $("#3EffectiveDate").val("01/01/" + (currentYear + 1));
        });
    });
share|improve this question

migrated from stackoverflow.com Feb 7 '12 at 19:26

This question came from our site for professional and enthusiast programmers.

1  
ID's can't start with a number. –  Kevin B Feb 7 '12 at 19:24
    
This really isn't something I'd worry about. Sure you could probably make it shorter but there's nothing particularly smelly about any of it. –  Spencer Ruport Feb 7 '12 at 19:25
    
@Spencer-Ruport thanks for pointing that out. that may be causing an error i have. –  Antarr Byrd Feb 7 '12 at 19:40

2 Answers 2

up vote 5 down vote accepted

Since your code is all the same, you can dynamically create your selector:

...

$( '#0LevelId,#1LevelId,#3LevelId' ).change( function(){
    ...
    $( '#' + this.id.substr( 0, 1 ) + 'EffectiveDate' )...
} );
share|improve this answer
    
Nice suggestion! –  Antarr Byrd Feb 7 '12 at 19:34
    
-1 .. you should use class instead fixed IDs –  tereško Feb 7 '12 at 20:10
2  
@teresko -- that assumes an associated DOM structure that the OP doesn't state he has. e.g. the ability to write code like $( this ).find( '.effectiveDate' ). Since no structure is given, I gave code based on the OP's code instead of telling him to potentially "refactor everything and do this" –  zyklus Feb 7 '12 at 20:35

Since you're setting the min-width attribute only once and at the start, consider adding this property to an actual css.

Also, as cwolves noticed, you can select all three elements at once. But instead of specifing them by comma, make all the element to be of the same class.

Besides that, it is a good practice to learn about jQuery's selectors before using it, because otherwise you're kind of missing the whole point of the library.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.