2010-07-13 53 views
1

我有兩個輸入字段holidayDate和說明(ID =標籤)JavaScript驗證

<html> 
    <head> 
     <script type="text/javascript"> 
      $(document).ready(function() { 
       $('#holidayDate').datepicker(); 
       var availableTags = ["New years Day", "Martin Luther King Day","Groundhog  Day", "Valentine's Day", "Washington's Birthday", 
       "Easter", "Earth Day", "National Arbor Day", "Mother's Day", "Memorial Day", "Flag Day", "Father's Day", "Independence Day", 
       "Labor Day", "Columbus Day", "Halloween", "Veterans Day", "Thanksgiving Day", "Pearl Harbor Remembrance Day", "Christmas Day"]; 
       $("#tags").autocomplete({source:availableTags}); 
       $('#holidayDate').change(function() { 
        var dateString = $(this).val().substring(0, 5); 
        var res = ""; 
        switch (dateString) { 
         case '01/01': res = availableTags[0]; break; //If date entered, then return holiday 
         case '02/02': res = availableTags[2]; break; 
         case '02/14': res = availableTags[3]; break; 
         case '04/22': res = availableTags[6]; break; 
         case '06/14': res = availableTags[10]; break; 
         case '07/04': res = availableTags[12]; break; 
         case '10/31': res = availableTags[15]; break; 
         case '11/11': res = availableTags[16]; break; 
         case '12/07': res = availableTags[18]; break; 
         case '12/25': res = availableTags[19]; break; 
        }   
        $('#tags').val(res); 
       }); 
      }); 
     </script> 
    </head> 
    <body> 
     <input id="holidayDate">Date:</input> 
     <input id="tags">Description:</input> 
    </body> 
</html> 

如果我想要做相同的驗證反之亦然那麼我該怎麼辦?

回答

0

我建議你把相應的日期到另一個數組,像這樣:

var tagDates = [ '01/01', null, '02/02', '02/14', ... ]; 
/* fill in the rest, with null where you don't have a date */ 

然後,你可以只遍歷數組要麼取決於你想要什麼。您現有的switch會變成這樣:

/* convert date to tag */ 
for (var i = 0; i < tagDates.length; i++) 
    if (tagDates[i] == dateString) { 
    res = availableTags[i]; 
    break; 
    } 

你可以圓像這樣做的另一種方式:

/* convert tag to date */ 
for (var i = 0; i < availableTags.length; i++) 
    if (availableTags[i] == tagString) { 
    res = tagDates[i]; 
    break; 
    }