HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

jQuery date split into day month year

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
yearintodatesplitjquerymonthday

Problem

I'm changing an HTML datepicker value (#date) into 3 separate values in order to post them to a booking engine. I've managed to get it to work but there is a lot of repetition and the original #date value is also submitted unnecessarily.

The engine takes these parameters:

date_day=27&date_month=9&date_year=2013&nights=3&people=2&ref=558&langClient=eng&expr=EUR`


HTML

            
                
                
                Date :
                

                
                Nights :
                 

                
                Guests : 
                                                       

                 
                
                
                Currency : 
                    
                        EURO
                        US Dollar
                        Argentine Peso
                        Australian Dollar
                        
                
                

                                    

    


jQuery

$('#date').on('change', function() {
     var new_val = $(this).val().split('-'),
         dateYear = parseInt(new_val[0]),
         dateMonth = parseInt(new_val[1]),
         dateDay = parseInt(new_val[2]);

    $('', {
        type: 'hidden',
        name: 'date_day',
        id: 'date_day',
        value: dateDay

    }).appendTo('#anchor');

    $('', {
        type: 'hidden',
        name: 'date_month',
        id: 'date_month',
        value: dateMonth

    }).appendTo('#anchor');

    $('', {
        type: 'hidden',
        name: 'date_year',
        id: 'date_year',
        value: dateYear

    }).appendTo('#anchor');

 });

Solution

The tought process to make your code DRY is almost always the same:

  • Find the commonalities between blocks of code.



  • Extract these into an iterable structure.



  • Loop.



Here we can see that everything is the same except the prefix and the value.

The code could be changed to:

Please note that you should always specify the radix argument when using the parseInt function since 10 is not default in every browser.

$('#date').on('change', function() {
    var newVal = $(this).val().split('-'), //renamed new_val to newVal, always stick to one naming convention
        dateParts = {
            year: parseInt(newVal[0], 10),
            month: parseInt(newVal[1], 10),
            day: parseInt(newVal[2], 10)
        };

    $('#anchor').append($.map(dateParts, function (index, key) {
        var name = 'date_' + key;

        return $('', {
            type: 'hidden',
            name: name,
            id: name,
            value: dateParts[key]
        });
    }));
});


EDIT:

Note that with the above logic, you will end up having duplicate inputs with different values if the user changes the value multiple times. You could solve this by removing the previously added inputs before adding the new ones, but you could also simply add the inputs just prior to form submission by listening to the submit event instead.

Also, if you want to avoid sending #date's value, you can disable that input before submitting; disabled inputs aren't sent to the server.

Finally, you could choose to simply submit the form in AJAX using $.ajax (or any of it's shortcut methods such as $.post). That would have the advantage of making your site slighlty more dynamic and you would not have to append inputs to the form since you can use the data option.

Code Snippets

$('#date').on('change', function() {
    var newVal = $(this).val().split('-'), //renamed new_val to newVal, always stick to one naming convention
        dateParts = {
            year: parseInt(newVal[0], 10),
            month: parseInt(newVal[1], 10),
            day: parseInt(newVal[2], 10)
        };

    $('#anchor').append($.map(dateParts, function (index, key) {
        var name = 'date_' + key;

        return $('<input>', {
            type: 'hidden',
            name: name,
            id: name,
            value: dateParts[key]
        });
    }));
});

Context

StackExchange Code Review Q#31990, answer score: 2

Revisions (0)

No revisions yet.