views:

364

answers:

3

Hi, i have some input fields like below:

<input type="text" name="date_1" class="dataList" value="2009-12-30" />
<input type="text" name="date_2" class="dataList" value="2007-06-12" />
<input type="text" name="date_3" class="dataList" value="2009-10-23" />


<input type="text" name="date_max" class="result" value="0000-00-00" />

I must to do something like this:

1) Add to array list of dates from all input fields with attribute class="dataList" (fields contain date in format yyyy-mm-dd)

2) Check that all fields are full and check if all dates are in good format(month not more than 12, day not maore than 31, lenght of all qual 10 chars)

3A) If conditions from second point are true then:

-sort the array from max to min value

-get the first element from array and set it to value of input with name="data_max"

3B) If conditions from second point are false then:

-get "0000-00-00" and set it to value of input with name="data_max"

I done all this things in PHP, but i want to do this in jQuery.

In jQuery i can update in real time the value of data_max field.

Please give me some suggestions what functions i should to use.

Regards, Pit

A: 

Hi there. I think you'll find that many of the tasks you describe could be accomplished if you spent a couple hours with some jQuery tutorials. The official tutorials are pretty good. "How jQuery Works" and "Getting Started with jQuery" are just fine. Google up some more if you are unsatisfied.

JavaScript's Date() object is notoriously ugly to use, but you'll likely have to use this.

1) This selector should let you gather all of your input values:

var dates = $('input.dataList, input.result');

2) I would suggest searching for existing date validation code rather than writing your own. If you find that this is difficult, then you could use the jQuery $.post method (to send your data to a PHP script, perform the validation there, and report the results back.

3) Sorting the array may require that you write a custom sort callback. This callback could work on an array of jQuery elements and use the val() method to extract these values.

jkndrkn
+2  A: 

Have a go of this...

<html>
    <head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"&gt;&lt;/script&gt;
    <script type="text/javascript">
        var dataList = new Array();
        $(document).ready(function()
        {
            update();
        });

        function update()
        {
            dataList = new Array();
            $('.dataList').each(function(i)
            {
                dataList[i] = this.value;
            });

            if(confirmDates(dataList))
            {
                // Perform sort from max to min
                dataList.sort();
                dataList.reverse();

                $("input[name$='date_max']").val(dataList[0]);
            }
            else
            {
                $("input[name$='date_max']").val("0000-00-00");
            }
        }

        function confirmDates(arrayList)
        {
            for(var i in arrayList)
            {
                // Check length is 10
                if(arrayList[i].length != 10)
                    return false;

                // Check month not more than 12
                var year = arrayList[i].substring(0, 4);
                var month = arrayList[i].substring(5, 7);
                var day = arrayList[i].substring(8, 10);

                if(parseInt(month) > 12 || parseInt(day) > 31)
                    return false;
            }

            return true;
        }
    </script>
</head>
<body>                                                       
    <input type="text" name="date_1" class="dataList" value="2009-12-30" />
    <input type="text" name="date_2" class="dataList" value="2007-06-12" />
    <input type="text" name="date_3" class="dataList" value="2009-10-23" />
    <input type="text" name="date_max" class="result" value="0000-00-00" />
    <button onclick="update()" value="Update" />
</body>
</html>
Ambrosia
`for..in` is more suitable for objects than arrays. Also, it is considered a "best practice" of sorts to validate each value `i` with `if ( !arrayList.hasOwnProperty(i) ) { continue; }`.
Justin Johnson
Best practise simply means there are other ways to do it, my code works and is fast, the fact that for..in works on arrays is because that is what it was designed to do, if not it would not allow it. I could have done a length check and used a normal for loop but that's generally uglier and more lines are needed. Your comment is welcome but hardly worth the vote down.
Ambrosia
I think that code of Ambrosia is the best because it's clear, simple, fast and working like I ask. Thank you.
pit777
If you like it and it is the preferred answer please vote it up again. Thanks
Ambrosia
+1  A: 

When working with Dates it is always best to try and use the Date objects that are available. The code below will do what you have asked except for the detailed errors on why a date is invalid.

If you want a more detailed error you can add to the getValidDateObject() method.

the dates are added to the array by their millisecond value since midnight of January 1, 1970 which is built in to javascript as per w3schools. This allows the dates to be sorted properly not just comparing strings.

Further once you are working with actual date objects you can change the getShortDateString() method to return in any format you wish!

Html Block

      Test Values<br />
      <input type="text" name="date_1" class="dataList" value="2009-12-30"> 
      <input type="text" name="date_2" class="dataList" value="2007-06-12">
      <input type="text" name="date_3" class="dataList" value="2009-10-23">
      <br />
      Max Date   
      <input type="text" name="date_max" class="result" value="">
      <br /><br />
      <a href='javascript:getMax();'>Find Max Date</a>

Main Function

function getMax(){  

    var dates = new Array(); 
    var dateStrings = $('.dataList');  

    $.each(dateStrings , function(i, date){ 
     var strDate = $(date).val();
     var objDate = getValidDateObject(strDate);

     if (!objDate){
      $("input[name$='date_max']").val('0000-00-00');
      throw new Error('Invalid Date: ' + strDate);
     }

     dates[i] =  objDate.getTime();   
    });

    dates.sort();
    dates.reverse();

    var d2 = new Date(dates[0]);
    var maxDateString = getShortDateString(d2);

    $("input[name$='date_max']").val(maxDateString); 
}

Return a valid Date Object

function getValidDateObject(strDate){

    strDate = strDate.replace(/[-]/g,'/')
var objDate = new Date(strDate);

    if (objDate == 'Invalid Date') {
     alert('bad input: ' + strDate);   
     return false;
    }
    return objDate; 
}

Return a formatted Date String

function getShortDateString(objDate){
        var y = objDate.getFullYear();
        var m = objDate.getMonth() + 1;
        var d = objDate.getDate();

        if (m < 10) m = "0" + m; 
        if (d < 10) d = "0" + d;

        var strDate = y + '-' + m + '-' + d;

        return strDate;
}
Bobby Borszich